Rotating and moving an image in a canvas element?

后端 未结 1 827
天命终不由人
天命终不由人 2021-01-13 18:30

I would like to move and rotate an image of a ball in a element. The ball is 68x68 and the canvas is 300x200. The ball moves along the x and y axis, flipping its x and y

相关标签:
1条回答
  • 2021-01-13 19:11
    1. Translate the context to the point on the canvas that the object should rotate about.
    2. Rotate the context.
    3. Either:
      • Translate the context by the negative offset within the object for the center of rotation, and then draw the object at 0,0, or
      • Draw the image using the negative offset within the object for the center of rotation.

    e.g.

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

    Note that if you need absolute speed, instead of saving and restoring the canvas (handling many properties that you didn't change) you can just undo 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 has been blindly parroted from someone else; I have not personally benchmarked to verify that it is correct.

    Edit: I've added a mocked up working example of this here: http://phrogz.net/tmp/canvas_beachball.html

    0 讨论(0)
提交回复
热议问题