Rotate an image around its center in canvas

后端 未结 3 1185
暖寄归人
暖寄归人 2020-12-10 12:56

I\'m trying to do my first image animation on canvas. I want the image to rotate but something is not correct in my code. Any ideas? This is all in a jquery document ready:

3条回答
  •  情深已故
    2020-12-10 13:40

    Based on the comments above, but a bit more simple and in vanilla. This one worked for me perfectly. Of course you should use clearRect in order to erase the canvas on each rendering.

    var canvas = document.querySelector('#my-canvas');
    var ctx = canvas.getContext('2d')
    var ang = 0
    
    function rotateAndRenderImg() {
        var img = document.querySelector('img')
        ctx.save()
        var pos = {x: desiredRenderPosX, y: desiredRenderPosY}
        ctx.translate(pos.x ,pos.y)    
        ctx.rotate(Math.PI / 180 * (ang += 5))
        ctx.drawImage(img, -img.width / 2, -img.height / 2, img.width, img.height)
        ctx.restore()
    }

提交回复
热议问题