Amit Kanfer
Amit Kanfer

Reputation: 41

How to move a drawn image on HTML5 canvas?

Assuming i have an HTML5 canvas on which i've already drawn multiple images, and i don't have the final resulting image "in hand", and now i want to move the whole image in the canvas up? (just if like the user chose to 'scroll down' the image)

If i had the final image, i could have clear the canvas and draw it again in a 'y' coordinate which is negative, that'll work. The problem is that calling toDataUrl() in order to get the final image - is very CPU consuming.

Any other way to achieve this? Why can't i just tell the canvas to 'move everything up / down' by x pixels...?

thanks!

Upvotes: 1

Views: 7637

Answers (2)

potatopeelings
potatopeelings

Reputation: 41065

You can use ctx.getImageData (https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/getImageData) to get the image data and ctx.putImageData (https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/putImageData) to put the image data where you want.

Edit

Kaido's solution is the better alternative though.

Reference

Why is putImageData so slow?

Upvotes: 1

Kaiido
Kaiido

Reputation: 136698

Canvas drawImage() method accept an other canvas as source.
You can also draw the canvas on itself, but at each iteration, your image will have changed.

So the easiest way is to create an other canvas, which will keep your actual canvas image, and draw this new canvas to the one in the document :

var canvas = document.querySelector('canvas'),
  ctx = canvas.getContext('2d'),
  img = new Image(),
  // a ghost canvas that will keep our original image
  gCanvas = document.createElement('canvas'),
  gCtx = gCanvas.getContext('2d');
gCanvas.width = canvas.width;
gCanvas.height = canvas.height;


img.onload = function() {
  ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
  gCtx.drawImage(canvas, 0, 0, canvas.width, canvas.height);
  requestAnimationFrame(moveUp);
}
img.src = "http://lorempixel.com/200/200";

var y = 0;
function moveUp() {
  if (--y < (canvas.height * -0.5)) return;
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.drawImage(gCanvas, 0, y, canvas.width, canvas.height);
  requestAnimationFrame(moveUp)
}
<canvas width=200 height=200></canvas>

Upvotes: 4

Related Questions