Francis Snipe
Francis Snipe

Reputation: 551

Rotate an html5 canvas without redrawing the elements on canvas

I'm not sure if this is possible, I can't find any examples.

I want to create a spinning wheel on an html5 canvas. There will be 100 objects and images on the wheel. The wheel needs to spin fast. I don't want to have to redraw all 100 objects and images for each movement of the wheel. How can I rotate the wheel without constantly redrawing everything?

Here's some code:

var can = document.getElementById("canvas"),
con = can.getContext("2d"),
angle = 0;

con.fillStyle = "rgba(0, 0, 0, 0.2)";
con.fillRect(0, 0, can.width, can.height);
con.fillStyle = "#fff";
con.fillRect(0, 0, 200, 200);
con.fillStyle = "red";
con.fillRect(10, 10, 120, 120);
con.fillStyle = "blue";
con.fillRect(20, 20, 30, 30);

setInterval(function(){
  angle-=(Math.PI/3)/10; 
  con.save();
  con.translate(10,10);
  con.rotate(angle);
  con.restore();
},10);

Here's a jsFiddle: http://jsfiddle.net/CfbS3/.

Upvotes: 0

Views: 832

Answers (2)

atmin
atmin

Reputation: 370

Make an image of your elements in complete and rotate the image afterwards.

function createImage() {
    var image = new Image();
    var imgTmpCanvas = document.createElement("canvas");
    // imgTmpCanvas.setAttribute(...);
    var tmpCtx = imgTmpCanvas.getContext('2d');
    // now paint on tmpCtx as usual
    image.src = imgTmpCanvas.toDataUrl("image/png");
    return image;
}

Should work.

Upvotes: 4

Markku Kero
Markku Kero

Reputation: 391

Probably the best thing to do, if you really don't want to change the actual contents of the canvas, is to just draw the contents once (like you do above), and then to rotate the canvas itself as an HTML element. So you could modify your sample code and write your setInterval instead as follows:

setInterval(function(){
  angle-=(Math.PI/3)/10; 
  document.getElementById("canvas").style["transform"] = "rotate(" + angle + "rad)";
},10);

This should rotate fast and nicely. For Safari support you may need to also add:

document.getElementById("canvas").style["webkitTransform"] = "rotate(" + angle + "rad)";

Upvotes: 0

Related Questions