Reputation: 15
I'm learning javascript right now so I'm still new at this. I have an image I drew in an HTML canvas. They are the same size but to reduce the code i was wondering if it's possible to turn one in a var and just adjust the position of the second one?
heres my code:
// Cloud 1
ctx.beginPath();
ctx.fillStyle = "#fff";
ctx.ellipse(320, 170, 38, 25, 0 * Math.PI/180, 0, 2 * Math.PI);
ctx.ellipse(340, 156, 32, 35, 0 * Math.PI/180, 0, 2 * Math.PI);
ctx.ellipse(368, 174, 32, 26, 0 * Math.PI/180, 0, 2 * Math.PI);
ctx.ellipse(390, 174, 32, 26, 0 * Math.PI/180, 0, 2 * Math.PI);
ctx.ellipse(392, 173, 30, 26, 0 * Math.PI/180, 0, 2 * Math.PI);
ctx.fill();
// Cloud 2
ctx.beginPath();
ctx.fillStyle = "#fff";
ctx.ellipse(720, 100, 38, 25, 0 * Math.PI/180, 0, 2 * Math.PI);
ctx.ellipse(740, 86, 32, 35, 0 * Math.PI/180, 0, 2 * Math.PI);
ctx.ellipse(768, 104, 32, 26, 0 * Math.PI/180, 0, 2 * Math.PI);
ctx.ellipse(790, 104, 32, 26, 0 * Math.PI/180, 0, 2 * Math.PI);
ctx.ellipse(792, 103, 30, 26, 0 * Math.PI/180, 0, 2 * Math.PI);
ctx.fill();
Upvotes: 1
Views: 39
Reputation: 148
var clouds = [];
clouds.push({x: 320, y: 170});
clouds.push({x: 324, y: 156});
....
....
for (cloud = 0; cloud <10; cloud++){
ctx.ellipse(clouds[cloud].x, clouds[cloud].y, 30, 26, 0 * Math.PI/180, 0, 2 * Math.PI);
}
Upvotes: 1
Reputation: 4049
You can get the current image data of the canvas and put it back in a different place:
var data = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.putImageData(data, deltaX, deltaY);
Where deltaX and deltaY are how much you want to move your image horizontally and vertically.
In your case deltaX is 400, deltaY is -70.
Upvotes: 1