Canvas - permanently apply Y-axis offset to all future drawings

I want to have everything drawn onto the canvas be given an offset in the Y axis which will increase each frame, imagine gravity (without acceleration, just constant speed) and there's no ground at the bottom of the canas to prevent objects from falling off. I want this to apply to everything, not just some drawings, not just stuff in the foreground, I want the entire canvas to shift down by a fixed number of pixels every animation frame. I thought I might be able to do this by using ctx.translate(0, 10) without wrapping it in save/restore, but this hasn't seemed to work. Here's a snippet from one of my draw functions in case anything here is causing issues;
canvas.ctx.save();
canvas.ctx.translate(this.position.x, this.position.y);
canvas.ctx.rotate((this.position.angle * Math.PI) / 180);
canvas.ctx.beginPath();
canvas.ctx.rect(-15, -25, 30, 50);
canvas.ctx.fillStyle = "#000000";
canvas.ctx.fill();
canvas.ctx.closePath();
canvas.ctx.restore();
canvas.ctx.save();
canvas.ctx.translate(this.position.x, this.position.y);
canvas.ctx.rotate((this.position.angle * Math.PI) / 180);
canvas.ctx.beginPath();
canvas.ctx.rect(-15, -25, 30, 50);
canvas.ctx.fillStyle = "#000000";
canvas.ctx.fill();
canvas.ctx.closePath();
canvas.ctx.restore();
canvas.ctx is a CanvasRenderingContext2D for my canvas. My animation frame loop has the following;
function animate() {
canvas.ctx.translate(0, 10); // this appears to do nothing, does `.translate()` reset itself each call?
thatDrawFunction();
requestAnimationFrame(animate);
}
function animate() {
canvas.ctx.translate(0, 10); // this appears to do nothing, does `.translate()` reset itself each call?
thatDrawFunction();
requestAnimationFrame(animate);
}
of course, this is minimum reproduction, my actual code spans way too much to put in this thread
5 Replies
MarkBoots
MarkBoots3y ago
Think something like this should work. Clear the canvas, save, translate by amount * frameIndex, draw the thing and restore. then call the function again with increased frameIndex
function animate(frameIndex = 0) {
canvas.ctx.clearRect(0, 0, canvas.width, canvas.height);
canvas.ctx.save();
canvas.ctx.translate(0, 10 * frameIndex);
thatDrawFunction();
canvas.ctx.restore();
requestAnimationFrame(()=> animate(++frameIndex));
}
function animate(frameIndex = 0) {
canvas.ctx.clearRect(0, 0, canvas.width, canvas.height);
canvas.ctx.save();
canvas.ctx.translate(0, 10 * frameIndex);
thatDrawFunction();
canvas.ctx.restore();
requestAnimationFrame(()=> animate(++frameIndex));
}
small example: (removed pen, see screenshot below)
MarkBoots
MarkBoots3y ago
What is ss?
MarkBoots
MarkBoots3y ago
pen removed, backup
WillsterJohnson (@me in replies)
sorry, my laptop likes to focus the wrong window, I think I was playing a game? idk I ended up coming across something similar to that on SO, this seems to be cleaner though!

Did you find this page helpful?