Shifting an image with canvas
As part of my Tile Editor I needed a way to shift an image by x pixels left, right, up or down. I didn’t need to move the image, I needed to shift the pixels of the image. This allows you now to shift the image and thus makes painting seamless tiles much easier.
This would make our first example of shifting 100px to the left the following:
<script src="canvasshift.js"></script>
<script>
let c = document.createElement('canvas');
let cx = c.getContext('2d');
document.body.appendChild(c);
let i = new Image();
i.src = 'puking-unicorn.jpg';
i.onload = function() {
c.height = i.naturalHeight;
c.width = i.naturalWidth;
cx.drawImage(i, 0, 0);
canvasshift(c, -100, 0);
}
</script>
For other shifting, use different parameters. For example to shift the image 100 pixels to the right and 20 pixels up, you use canvasshift(c, 100, -20), to move 15px left and 20px down, canvasshift(c, 15, 20) and so on…
If the loading part is annoying to you, you can also use the load method of the script:
let c = document.createElement('canvas');
document.body.appendChild(c);
const shift = _ => {
canvasshift(c, -200);
}
canvasshift.load(c, 'puking-unicorn.jpg', shift);
This one takes three parameters, of which the last one is optional. The first is the canvas, the second the url of the image (this needs to be on the same domain – or a cors-enabled one) and a callback method that will be called once the image was successfully loaded.
Summary
Whilst CSS should be enough in most of the cases you want to do some image shifting, this should get you on the way. There are more options in canvas like defining images as patterns an using transform, but for non-animated shifting this seems to be the easiest option.