watermarkjs icon indicating copy to clipboard operation
watermarkjs copied to clipboard

How to make watermark cover 100% width?

Open ohabash opened this issue 6 years ago • 1 comments

My users will be uploading different size images. Is there a way to make sure either we resize the uploaded image OR make the watermark cover 100% width?

ohabash avatar Jul 16 '18 19:07 ohabash

Hi, I am not make the watermark cover 100% width, but I got resize the watermark. Here is what I do:

1. Using image(draw) to customize my watermark process.

I found documentation got this method, then I use it to customize my process:

// place a watermark in the upper left hand corner of an image
watermark(['/img/coffee.jpg', '/img/logo.png'])
  .image(function (coffee, logo) {
    var context = coffee.getContext('2d');
    context.save();

    context.globalAlpha = alpha;
    context.drawImage(logo, 10, 10);

    context.restore();
    return target;
  });

2. Using drawImage() to resize.

I found drawImage() on MDN, which parameters could control the size of the image you draw, that size is based on the canvas size. For example, your canvas's width is 700, and if you want your watermark cover 100% width, you should add 700 to your forth parameters in drawImage().

Btw, you may try it how the size effecting on Chinese version MDN

3. Example and code.

Here is my code with integration of Vue.js and Vue-croppa:

async addWatermark() {
  const originalImg = this.$refs.myCroppa.generateDataUrl()
  const watermarkedImage = await watermark([originalImg, this.pngFile])
      .image((uploadImage, logo) => {
        const context = uploadImage.getContext('2d')
        const canvas = this.$refs.myCroppa.getCanvas()
        const logoResizedHeight = canvas.height * 0.75
        const logoResizedWidth = canvas.width / 2
        const posX = (uploadImage.width - logoResizedWidth) / 2
        const posY = (uploadImage.height - logoResizedHeight) / 2

        context.save()

        context.globalAlpha = 0.4
        context.drawImage(logo, posX, posY, logoResizedWidth, logoResizedHeight)

        context.restore()
        return uploadImage
      })
      .then(img => img)

  this.watermarkedImage = watermarkedImage
  this.$refs.myCroppa.refresh()
}

Hope my experience will be useful for you :)

nereuseng avatar Jan 03 '19 10:01 nereuseng