Reputation: 283
I'm trying to create some of rotating images. So I create an array of canvases and put in each picture. But for some reason they are not displayed. Help me please.
var canvas = [], ctx = [], particles = [];
for (var i = 0; i < 10; i++){
sym.$( sym.$("Rectangle") ).append('<canvas id="partical' + i + '"></canvas>');
canvas.push(document.getElementById("partical" + i));
canvas[i].width = 550;
canvas[i].height = 400;
ctx[i] = canvas[i].getContext("2d");
}
for(var i = 0; i < 10; i++){
particles.push({
x: Math.random()*canvas[i].width, //x-coordinate
y: Math.random()*canvas[i].height, //y-coordinate
img: new Image()
})
particles[i].img.src = "images/Flake" + Math.floor(Math.random()*4+1) + ".png";
}
function draw(){
for(var i = 1; i < 10; i++){
ctx[i].clearRect(0, 0, canvas[i].width, canvas[i].height);
var p = particles[i];
ctx[i].drawImage(p.img,p.x,p.y,50,50);
ctx[i].fill();
}
}
draw();
Upvotes: 2
Views: 405
Reputation: 5897
jsFiddle : https://jsfiddle.net/CanvasCode/u0p9wtut/
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var Particle = function(xSet, ySet)
{
this.XPos = xSet;
this.YPos = ySet;
this.Sprite = new Image();
this.Sprite.src = "http://s.cdn.gaiaonline.com/images/thumbnails/85449184bbb9.png";
this.Rotation = 0;
}
var particles = new Array();
for(var i = 0; i < 10; i++){
particles.push(new Particle(Math.random()*c.width, Math.random()*c.height));
}
function draw()
{
ctx.fillStyle = "#000";
ctx.fillRect(0,0,c.width,c.height);
for(var i = 0; i < particles.length; i++)
{
var particle = particles[i];
particle.YPos += 1;
// Draw image rotated
ctx.save();
ctx.save();
ctx.translate(particle.XPos + particle.Sprite.width / 2, particle.YPos + particle.Sprite.height / 2);
ctx.rotate( particle.Rotation );
ctx.translate(-(particle.XPos + (particle.Sprite.width / 2)), -(particle.YPos));
ctx.drawImage(particle.Sprite, particle.XPos, particle.YPos);
ctx.restore();
ctx.restore();
if(particle.YPos > c.height)
{
particle.YPos = 0;
particle.XPos = Math.random()*c.width;
}
particle.Rotation += 0.01;
}
}
setInterval(draw, 3);
What you can do is use the ctx.save
, ctx.restore
and ctx.translate
, you simply first save your canvas context so we can reload it later, we then translate the canvas, basically a translate is like setting an offset on where the image is drawn, we set the translate position to the center of the sprite, then we rotate the image around (the translate means we will rotate the image around its centre point). We then once again update the translate, draw the image rotated and then restore the canvas context because we may want to draw something else. If we don't restore the context then the next image that was draw would take into account the translate and rotate.
Upvotes: 1