preface

In order to prevent information leakage or intellectual property infringement, it is necessary to add watermarks to pages and images in the World of the Web. Here is a simple way to add a page watermark to the front end.

Technical analysis

The desired effect is to add watermark information to the box that needs to be loaded. The first solution that comes to mind is to add a new box, create a background picture containing watermark information through canvas, and fill it with the elements that you want to add watermark. Then set the watermark to the background image.

Implementation scheme

The implementation code


// Configuration example
{
    container = document.body, 
    width = '200px'.// The watermark width
    height = '148px'.// The watermark width
    textAlign = 'content'.// Watermark direction
    textBaseline = 'middle', 
    font = '16px Microsoft Yahei'.// Watermark font format
    content = 'watermark'.// Watermark the content
    rotate = '45'.// Font tilt Angle
    zIndex = 10000,}// Implementation code
const canvasInfo = function({
   container = document.body,
   width = '200px',
   height = '148px',
   textAlign = 'content',
   textBaseline = 'middle',
   font = '16px Microsoft Yahei',
   content = 'watermark',
   rotate = '45',
   zIndex = 10000} = {},) {
   const canvas = document.createElement('canvas'); / / create a canvas
   canvas.setAttribute('width', width); // Add canvas property
   canvas.setAttribute('height', height);
   const ctx = canvas.getContext('2d');
   ctx.textAlign = textAlign;
   ctx.textBaseline = textBaseline;
   ctx.font = font;
   ctx.rotate((Math.PI / 180) * rotate); // Rotate the Angle
   ctx.fillText(content, parseFloat(width) / 2.parseFloat(height) / 2);
   const base64Url = canvas.toDataURL()
   const watermarkDiv = document.createElement('div');
   const styleStr =
	` position:fixed;
	  top:0;
	  left:0;
	  bottom:0;
	  right:0;
	  width:100%;
	  height:100%;
	  z-index:${zIndex};
	  background-image:url('${base64Url}');
	  opacity: 0.1; 
	 `;
   watermarkDiv.setAttribute('style', styleStr);// Add the div attribute
   container.insertBefore(watermarkDiv, container.firstChild); // Insert into the list
		}
   canvasInfo()
Copy the code

Display effect

conclusion

Canvas painting directly avoids the creation and addition of a large number of DOM elements in the case of high watermark density.