How to Watermark a Picture with Canvas?

How to use canvas to watermark pictures in the front end? The following article will introduce you to the method of adding a watermark to a picture using canvas. There is a certain reference value, friends in need can refer to it, I hope to help everyone.


Adding a watermark to a webpage image in the front end is a common feature and one of the ways that Internet content authors protect their copyrights. This article briefly records the implementation of watermarking on the front end using canvas.

The canvas element is actually a canvas. We can easily draw some text, lines, graphics, etc. It can also draw an image rendered in an img tag on the canvas.

When uploading a file to the backend, after reading the user’s local file using the input tag, it is actually a Blob object (more precisely, a File object, a special Blob object); and an image is displayed on the page using img Labels; drawing functions are implemented with canvas. The function of adding watermarks needs to convert between the img tag, canvas, and Blob objects. This can be done through some APIs:


We can read the image blob locally, then render it to the img tag, use canvas to draw the img content and draw the watermark content to the canvas, and then convert the canvas content to a Blob object upload server, so that the function of image + watermark is fully implemented.

First, read the image file locally and render it to the img tag

Reading the image file locally will get a Blob object. We can use the FileReader.readAsDataURL method to read the content of the Blob and get a Base64 encoded file content. This content can be assigned to img.src to be rendered on the browser. Local image. Of course, img does not have to be rendered into the DOM tree. The read operation is an asynchronous operation. The load event is triggered when the read is completed. In order to facilitate subsequent calls, we can wrap this operation with a Promise and finally return a Promise object.

function blobToImg (blob) {
  return new Promise ((resolve, reject) => {
    let reader = new FileReader ()
    reader.addEventListener ('load', () => {
      let img = new Image ()
      img.src = reader.result
      img.addEventListener ('load', () => resolve (img))
    reader.readAsDataURL (blob)

Second, draw the img tag content to the canvas canvas

Calling the drawImage method of the canvas context object of the canvas element can be used to draw the img content to the canvas.

function imgToCanvas (img) {
  let canvas = document.createElement ('canvas')
  canvas.width = img.width
  canvas.height = img.height
  let ctx = canvas.getContext ('2d')
  ctx.drawImage (img, 0, 0)
  return canvas

The drawImage method can pass multiple parameters to define the range of the image to be drawn. Here, 0, 0 is defined to start drawing from the upper left corner of the image, and two parameters can be passed to define the end point of the image drawing, but here The entire picture is drawn to the canvas, so the default value is sufficient.

Third, draw a watermark on the canvas and convert it to a Blob object

When uploading images, we usually use FormData, and the image file is put into FormData as a Blob object, so we need to convert the canvas to Blob for file upload and other operations. Using the HTMLCanvasElement.toBlob method:

function watermark (canvas, text) {
  return new Promise ((resolve, reject) => {
    let ctx = canvas.getContext ('2d')
    // Set fill size and font, style
    ctx.font = "24px Times New Roman"
    ctx.fillStyle = "# FFC82C"
    // Set right alignment
    ctx.textAlign = 'right'
    // Draw text at the specified position, here specify the location from the bottom right corner 20 coordinates
    ctx.fillText (text, canvas.width-20, canvas.height-20)
    canvas.toBlob (blob => resolve (blob))

Fourth, a complete example of watermarking in pictures

The above three steps are combined to complete the watermarking from the picture. The following is a simple use example: select an image file locally, then add the watermark, and preview the added watermark under the incoming dom element image.

function imgWatermark (dom, text) {
  let input = document.createElement ('input')
  input.setAttribute ('type', 'file')
  input.setAttribute ('accept', 'image / *')
  input.onchange = async () => {
    let img = await blobToImg (input.files [0])
    let canvas = imgToCanvas (img)
    let blob = await watermark (canvas, text)
    // Here read the blob to the img tag and render it in the dom; if it is an upload file, you can add the blob to FormData
    let newImage = await blobToImg (blob)
    dom.appendChild (newImage)
  } ()

Add a div element with the container id to the page and call it as follows:

let dom = document.querySelector ('# container')
imgWatermark (dom, 'Watermark text')

This completely adds a watermark effect to the picture. Let’s take a look at the actual effect below, and you can also experience it online .

Before adding a watermark:

Before adding a watermark

After adding a watermark (watermark content: “”):

After adding a watermark

Five. Summary

This article only introduces the simple implementation of image + watermark text, only some examples are introduced, in fact, more complex watermark effects can be achieved, such as images, translucent or gradient text, but the principle is the same. In addition, some of the interfaces involved in this article are actually very useful. For example, a common function is preview and crop of avatar upload. At this time, you can use FileReader to read the preview of the file content, and use CanvasRenderingContext2D.drawImage to implement the crop function. For more detailed usage of the interfaces involved in this article, you can refer to the MDN documentation. The APIs in this article use the form of links. You can quickly view their documentation.

#watermark #html #canvas

How to Watermark a Picture with Canvas?
58.80 GEEK