Malek Alashkar
Malek Alashkar

Reputation: 41

Rotate an image horizontally in node-canvas?

enter image description here

enter image description here

I need help doing something like this with node-canvas. Just flipping the image to be looking the other way.

Upvotes: 1

Views: 1493

Answers (1)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48693

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.sstatic.net/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>

Upvotes: 2

Related Questions