Did you know that you can add a watermark to all of your images that are on the same domain as your site just using JavaScript? Thanks to the <canvas> we can modify images and present in various ways as if they were originally available that way all via JavaScript. The following function is a quick-and-dirty example of how to leverage the canvas to add a watermark to an <img>:

Now let’s use this watermarkImage() function on an image found under the same domain:

Original Watermarked

By using the code below we end up getting the watermarked image above on the right showing the neighborhood of Ensanche Espaillat (Santiago de los Caballeros, Dominican Republic):

var elemImg = document.getElementById('imgToWatermark');
watermarkImage(elemImg, 'Ensanche Espaillat');

Of course, this simple function is not a fully featured solution for adding watermarks to our images. For example the following cases may occur:

  • We just want to create a watermarked image from an image URL.
  • We want to change the background color of the watermark.
  • We want to use a logo image as the watermark.
  • etc., etc.

If the watermarkImage() function works the watermark will be added to the image, but if not the image will not be changed. This is done on purpose to avoid strange behaviour on failure. There are two main reasons why this would fail:

  1. The image you want to watermark is not under the same domain as the page running the JavaScript code.
  2. The browser running the code doesn’t support adding images and/or SVGs to a <canvas>.

There is actually a great solution out there called watermark.js which will probably provide all of the options that you need to watermark your images.

Of course, if you would like to write your own code, my gist at the beginning of this post should be a pretty good start. Have fun and happy coding! 😎

Categories: BlogJavaScript


bigo · June 12, 2017 at 7:48 PM

cool technique 🙂


Bram de Haan · June 17, 2017 at 4:10 PM

Made a demo for this on Codepen codepen.io/atelierbram/pen/RgKLZK

Leave a Reply

Your email address will not be published. Required fields are marked *