Skip to content

Instantly share code, notes, and snippets.

@sahilpaudel
Created May 27, 2020 16:41
Show Gist options
  • Save sahilpaudel/a3e775676e80b403d473f6894f22b6dc to your computer and use it in GitHub Desktop.
Save sahilpaudel/a3e775676e80b403d473f6894f22b6dc to your computer and use it in GitHub Desktop.
Watermark Using Canvas
const { createCanvas, loadImage } = require('canvas');
const drawWatermarkAsBuffer = (pathOfSourceImageFile, pathOfWaterMarkImageFile, width, height) => {
const canvas = createCanvas(width, height);
const ctx = canvas.getContext('2d');
// loading the source image file
return loadImage(pathOfSourceImageFile).then(loadSourceImage => {
// drawing the source file into canvas
ctx.drawImage(loadSourceImage, 0, 0, width, height);
// loading the watermark image file
return loadImage(pathOfWaterMarkImageFile).then(loadWatermarkImage => {
// drawing the watermark image over the source image
ctx.drawImage(loadWatermarkImage, 0, 0, width, height);
return canvas.toBuffer();
});
});
}
module.exports = {
drawWatermarkAsBuffer
}
@Bestulo
Copy link

Bestulo commented Mar 26, 2022

thank you hahah, berry useful

I hardcoded a few things, and lowered opacity for the watermark.

const { createCanvas, loadImage } = require("canvas");

const drawWatermarkAsBuffer = async (
  pathOfSourceImageFile,
  pathOfWaterMarkImageFile,
  width,
  height
) => {
  const canvas = createCanvas(width, height);
  const ctx = canvas.getContext("2d");
  ctx.globalAlpha = 1;

  // loading the source image file
  const loadSourceImage = await loadImage(pathOfSourceImageFile);
  // drawing the source file into canvas
  ctx.drawImage(loadSourceImage, 0, 0, width, height);
  ctx.globalAlpha = 0.5;
  const loadWatermarkImage = await loadImage(pathOfWaterMarkImageFile);
  // drawing the watermark image over the source image
  //                                x    y    w    h
  ctx.drawImage(loadWatermarkImage, 987, 427, 300, 300);
  return canvas.toBuffer();
};

module.exports = {
  drawWatermarkAsBuffer,
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment