Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate an image around its center in canvas

Tags:

People also ask

How do I rotate an image on canvas?

<canvas id="myCanvas" width="30" height="30">

How do you rotate a Rectanger in canvas?

To do that you need to first context. translate to the rect's centerpoint before rotating. // move the rotation point to the center of the rect ctx. translate( x+width/2, y+height/2 ); // rotate the rect ctx.


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:

var canvas = document.getElementById('logobg1');  
    var ctx = canvas.getContext('2d');

    var img = new Image();   // Create new Image object
    img.src = 'images/containerbg.png'; // Set source path // set img src

    img.onload = function(){ // when image loads
        ctx.drawImage(img,0,0);
        setInterval(function() {
            ctx.save();
            ctx.clearRect(-ctx.canvas.width/2, -ctx.canvas.height/2, ctx.canvas.width, ctx.canvas.height);
            ctx.drawImage(img,0,0);
            ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2); // set canvas context to center
            ctx.rotate(Math.PI / 180 * 0.5); // 1/2 a degree
            ctx.restore();
        }, 16);
    }