Rotating and moving an image in a canvas element?

I would like to move and rotate the image of the ball in the element. The ball is 68x68, and the canvas is 300x200. The ball moves along the x and y axis, turning its x and y speed when it hits the wall - it all works. I just can't figure out how to rotate over a movement.

My draw () function, which I call through window.setInterval every 30 ms, looks something like this:

var draw = function() { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.save(); ctx.rotate(ball_radians); ctx.drawImage(ball_img, x, y); ctx.restore(); // calculate new x, y, and ball_radians } 

This makes the ball fly around the screen, so I am clearly doing something wrong. What am I missing?

+4
source share
1 answer
  • Translate the context to a point on the canvas around which the object should rotate.
  • The rotation of the context.
  • Or:
    • Translate the context to a negative offset inside the object for the center of rotation, and then draw the object at 0,0 or
    • Draw the image using a negative offset inside the object for the center of rotation.

eg.

 ctx.save(); ctx.translate( canvasLocX, canvasLocY ); ctx.rotate( ballRotationInRadians ); ctx.drawImage( ball_img, -ballCenterX, -ballCenterY ); ctx.restore(); 

Please note: if you need absolute speed, instead of saving and restoring the canvas (processing many properties that you have not changed), you can simply cancel your work:

 ctx.translate( canvasLocX, canvasLocY ); ctx.rotate( ballRotationInRadians ); ctx.drawImage( ball_img, -ballCenterX, -ballCenterY ); ctx.rotate( -ballRotationInRadians ); ctx.translate( -canvasLocX, -canvasLocY ); 

The previous bit of premature optimization was blindly blown from someone else; I personally have not verified that this is correct.

Change I added an example of work here: http://phrogz.net/tmp/canvas_beachball.html

+12
source

Source: https://habr.com/ru/post/1335626/


All Articles