In front-end development, sometimes we need to add a watermark on the page to protect the copyright of the content or to remind users. This article will introduce a method to add a full-screen watermark to the page through canvas.

Implementation idea

We can achieve the effect of full-screen watermarking through the following steps:

  1. Create a canvas element and set the width, height, and style.
  2. Gets the 2D context of the canvas.
  3. Rotate the canvas by rotating to tilt the watermark.
  4. Set styles for fonts, colors, alignment, and more.
  5. Use the fillText method to draw watermark text on the canvas.
  6. Convert the canvas to a base64 image and set it as the background image of the page.

code implementation

复制代码function addWaterMarker(str) {    var can = document.createElement('canvas');    var body = document.getElementById("app");        body.appendChild(can);        can.width = 200;    can.height = 150;    can.style.display = 'none';        var cans = can.getContext('2d');    cans.rotate(-20 * Math.PI / 180);    cans.font = "16px Microsoft JhengHei";    cans.fillStyle = "rgba(17, 17, 17, 0.30)";    cans.textAlign = 'left';    cans.textBaseline = 'Middle';    cans.fillText(str, can.width / 6, can.height / 2);        body.style.backgroundImage = "url(" + can.toDataURL("image/png") + ")";}// 在页面加载完成后调用addWaterMarker方法,传入自定义的水印文字window.onload = function() {    addWaterMarker('张健振      测试中');}

How to use

  1. Copy the above code into your project.
  2. Put the code inapp替换为你实际的页面容器元素的ID。
  3. Call the addWaterMarker method and pass in the custom watermark text.

复制代码addWaterMarker('这是我的水印');

Precautions

  • Please make sure to call the addWaterMarker method after the page is loaded to avoid the issue of the element not loading.
  • You can adjust the width, height, font size, color and other styles of the canvas, as well as the content of the watermark, according to your needs.

summarize

Adding a full-screen watermark to a page via canvas is a simple and effective way to protect content copyright or alert users. With the methods described in this article, you can easily implement this functionality in front-end projects.