I need help doing something like this with node-canvas. Just flipping the image to be looking the other way.
Asked
Active
Viewed 1,174 times
1
-
Node or browser JS, the two are slightly different. If just Node, you can remove the JS tag and add the Node.js tag. You could do the same thing in browser canvas by flipping the X axis by setting a negative scale e.g. `ctx.scale(-1, 1)` – Mr. Polywhirl Jul 21 '20 at 15:30
1 Answers
2
You can reverse the image by translating the image to the far-right and then scaling it right-to-left along the x-axis.
const drawImage = (ctx, image) => {
let { width, height } = image
Object.assign(ctx.canvas, { width, height })
ctx.save()
ctx.translate(width, 0);
ctx.scale(-1, 1);
ctx.drawImage(image, 0, 0)
ctx.restore()
}
Demo
const getContext = (selector) =>
document.querySelector(selector).getContext('2d')
/* Derived from: https://stackoverflow.com/a/52060802/1762224 */
const loadImage = (url) => {
return new Promise(resolve => {
const image = new Image()
image.addEventListener('load', () => resolve(image))
image.src = url
})
}
const drawImage = (ctx, image, flipX, flipY) => {
let { width, height } = image
Object.assign(ctx.canvas, { width, height })
ctx.save()
if (flipX || flipY) {
ctx.translate(flipX ? width : 0, flipY ? height : 0)
ctx.scale(flipX ? -1 : 1, flipY ? -1 : 1)
}
ctx.drawImage(image, 0, 0)
ctx.restore()
}
loadImage('https://i.stack.imgur.com/wF6Vr.png')
.then(image => {
drawImage(getContext('.original'), image)
drawImage(getContext('.flipped-x'), image, true)
drawImage(getContext('.flipped-y'), image, false, true)
drawImage(getContext('.flipped-both'), image, true, true)
})
.in-line {
display: inline-block;
width: 20%;
}
<canvas class="in-line original"></canvas>
<canvas class="in-line flipped-x"></canvas>
<canvas class="in-line flipped-y"></canvas>
<canvas class="in-line flipped-both"></canvas>

Mr. Polywhirl
- 42,981
- 12
- 84
- 132
-
-
@Gershom Thanks, I saved/restored the state. I also wrapped the image loading in a promise. – Mr. Polywhirl Jul 21 '20 at 15:49