Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shift canvas contents to the left

Tags:

Is there an easy way to shift canvas contents to the left, dropping the leftmost pixels and moving all others to the left?

like image 277
thejh Avatar asked Dec 04 '11 16:12

thejh


People also ask

How do you move a canvas in HTML?

HTML | canvas moveTo() Method The canvas moveTo() method is used to move the path to the specified point in the canvas, without creating a line. After calling the moveTo() method, we can use stroke() method to draw the path on the canvas.


2 Answers

Using getImageData and putImageData you could easily implement a pixel-by-pixel shift. For instance:

// shift everything to the left:
var imageData = context.getImageData(1, 0, context.canvas.width-1, context.canvas.height);
context.putImageData(imageData, 0, 0);
// now clear the right-most pixels:
context.clearRect(context.canvas.width-1, 0, 1, context.canvas.height);
like image 142
James Clark Avatar answered Sep 21 '22 13:09

James Clark


If you want to move the whole contents you can use a copy global composite operation with a single drawImage(), drawing the canvas on itself. Doesn't appear to work in safari, but it is crazy fast in chrome.

ctx.globalCompositeOperation = "copy";
ctx.drawImage(ctx.canvas,-widthOfMove, 0);
// reset back to normal for subsequent operations.
ctx.globalCompositeOperation = "source-over"
like image 25
Tony Destro Avatar answered Sep 21 '22 13:09

Tony Destro