Next.js Discord

Discord Forum

How to rotate an image onclick, onclick again will pause the rotation? Onclick again will continue?

Unanswered
Greenish Elaenia posted this in #help-forum
Open in Discord
Greenish ElaeniaOP
I have two styles with "rotate: 0deg", "rotate: 360deg", "transition: all linear 20s" applied to the image, and a state that changes which of the two styles are applied.

const Style: { [key: string]: React.CSSProperties } = {
button: {
background: "none",
border: "none",
position: "relative",
width: "220px",
height: "220px",
},
rotate: {
position: "absolute",
top: "0",
left: "0",
zIndex: "2",
rotate: "360deg",
transition: "all 10s linear",
},
static: {
position: "absolute",
top: "0",
left: "0",
zIndex: "2",
rotate: "0deg",
transition: "all 0s",
}
};

-----

<Image
style={rotating ? {...Style.rotate, } : Style.static}
src={overlaySrc}
alt={"Shurangama mantra"}
height={220}
width={220}
loading={"eager"}>
</Image>

However, this only partially meets specs.
Currently, it restarts the rotation from 0 degree every time.

I need the image to remember and save the current degree and continue from say 30deg.

There's no way to programmically set the css value of "rotate"? Ideally we dont want to create 360 css definitions one for each deg

I was thinking we could use canvas, draw an image, and rotate it programically? but there's syntax issues; how do I add an image to a canvas? Following examples doing

'use client'

// component header, props, etc here
const canvasRef = useRef<HTMLCanvasElement>(null);

useEffect(() => {
if (canvasRef.current) {
const canvas = canvasRef.current;
const context = canvas.getContext('2d');
if (context == null) {
throw new Error('Could not get context');
} else {
const image = new Image();
image.src = "/my-image.png"
context.drawImage(image, 0, 0);
}}

seems to through a ton of typescript/nextjs errors

0 Replies