Is there an easy way to shift canvas contents to the left, dropping the leftmost pixels and moving all others to the left?
5 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);
-
No, I mean dropping them (as in "they're over the left border now, drop them"). But yes, this looks good.– thejhCommented Dec 6, 2011 at 15:26
-
Oh I see, I was thinking about the rightmost pixels. I'll remove that sentence from the answer. Commented Dec 6, 2011 at 15:31
-
Thanks for this answer. Very helpful. As an alternative to your clearRect() line to clear that one column of pixels, you can just put context.clearRect( 0, 0, context.canvas.width, context.canvas.height ) after the getImageData() and before the putImageData(). This has the advantage that you can shift the image around any amount in any direction without having to worry about which rect(s) to clear.– M KatzCommented Jul 15, 2015 at 5:57
-
This is prohibitively slow in comparison to other approaches -- thus other answers should be prioritized. Commented Jan 13 at 1:59
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"
-
4This is much faster than
getImageData()
/putImageData()
, but for best results you may want to setctx.imageSmoothingEnabled = false
to prevent antialiasing the copied image data. Commented Jun 30, 2017 at 21:41 -
This is much faster. Just remember to set your transform back to default before drawing, it'll save you time wondering why it doesn't work! Commented Feb 4, 2019 at 14:36
Check out this jsFiddle example which uses ctx.translate
and ctx.get/putImageData
.
source code here
How it was done:
If redrawing what you want to shift is not too slow, the canvas transform methods are worth using.
get/putImageData
will also work if you just want to shift the current contents of the canvas without redrawing. This is not without disadvantages; it must make a copy of the pixel region being moved and it cannot be used if you draw any images from an external domain on your canvas:
Whenever the getImageData() method of the 2D context of a canvas element whose origin-clean flag is set to false is called with otherwise correct arguments, the method must throw a SecurityError exception.
In case jsFiddle should ever fail, here's the code:
HTML:
<a href="javascript:doIt()">shift 25 pixels to the left using `translate`</a><br>
<a href="javascript:shiftImage()">shift 25 pixels to the left using `getImageData/putImageData`</a><br>
<canvas id="canvas" width="600" height="200"></canvas>
JS:
var canvas = document.getElementById( "canvas" ),
ctx = canvas.getContext( "2d" );
var xOff = 0;
var redraw = function() {
ctx.clearRect(0, 0, 600, 200);
ctx.save();
ctx.translate(xOff, 0);
ctx.font = "100px Arial";
ctx.fillText( "Google", 20, 130 );
ctx.restore();
};
window.doIt = function() {
xOff -= 25;
redraw();
}
redraw();
var shiftContext = function(ctx, w, h, dx, dy) {
var clamp = function(high, value) { return Math.max(0, Math.min(high, value)); };
var imageData = ctx.getImageData(clamp(w, -dx), clamp(h, -dy), clamp(w, w-dx), clamp(h, h-dy));
ctx.clearRect(0, 0, w, h);
ctx.putImageData(imageData, 0, 0);
}
window.shiftImage = function() {
shiftContext(ctx, 600, 200, -25, 0);
}
var shiftContext = function(ctx, w, h, dx, dy) {
var clamp = function(high, value) { return Math.max(0, Math.min(high, value)); };
var imageData = ctx.getImageData(clamp(w, -dx), clamp(h, -dy), clamp(w, w-dx), clamp(h, h-dy));
ctx.clearRect(0, 0, w, h);
ctx.putImageData(imageData, 0, 0);
};
window.shiftImage = function() {
shiftContext(ctx, 600, 200, -25, 0);
};
-
"If you can redraw what you want to shift, you should use the canvas transform methods." - why? I guess that, depending on my code, this might be really slow.– thejhCommented Dec 6, 2011 at 15:27
-
"This is not as desirable because it cannot be used if you draw any images from an external domain on your canvas" - valid concern, but this isn't what I'm doing. Also, I guess you could just transfer the image via JSONP for solving this.– thejhCommented Dec 6, 2011 at 15:29
-
1Your point about speed is valid; I guess it should say "if redrawing what you want to shift is not too slow." At the same time,
getImage
actually makes a copy of all the pixels in the specified image region; whether one is faster than the other will depend on the complexity of the image being drawn and the size of the region shifted. Commented Dec 6, 2011 at 16:55
Perfect guys and thanks. Here's a simplified version of ellisbben's code, works a treat for some scrolling graphs I've building:
function shift_canvas(ctx, w, h, dx, dy) {
var imageData = ctx.getImageData(0, 0, w, h);
ctx.clearRect(0, 0, w, h);
ctx.putImageData(imageData, dx, dy);
}
I happened to be wondering if there was a convenient way to do this. I ended up coming up with this translate function, which doesn't require any of the (very slow) image data functions:
function translate(x, y) {
ctxBuffer.clearRect(0,0,canvasBuffer.width,canvasBuffer.height); //clear buffer
ctxBuffer.drawImage(canvasDisplay,0,0); //store display data in buffer
ctxDisplay.clearRect(0,0,canvasDisplay.width,canvasDisplay.height); //clear display
ctxDisplay.drawImage(canvasBuffer,x,y); //copy buffer to display
}
I've made a quick demo of it here.