Recently, I encountered a requirement in a project, which required adding a tiled watermark to a picture.
Similar effect
The first thing that comes to mind is to use canvas to complete this function. Because I have never been exposed to canvas before, so when I do this function, I just learn step by step. The process is quite nice. Next, follow me to implement this step by step. Functions and discover some pitfalls of canvas.
Because this function requires some canvas-based APIs and does not involve any principle issues, I will directly paste the js code here.
var img = new Image();// Because the business in my project is to add watermarks to Taobao pictures, so here is a main image of Taobao products img.src = 'https://gd4.alicdn.com/imgextra/i3/155/O1CN01XKkJqL1D11wYZbeI2_!!155-0-lubanu.jpg_400x400.jpg';img.onload = () => { // Prepare canvas environment var canvas = document. getElementById(myCanvas); var ctx = canvas.getContext(2d); // First draw the image to the canvas ctx.drawImage(img, 0, 0, 200, 200); // Draw the watermark to the canvas for (let i = 0; i < 20; i++ ) { ctx.rotate((-45 * Math.PI) / 180); // Initial deflection angle of watermark ctx.font = 20px microsoft yahei; ctx.fillStyle = rgba(0,0,0,0.5); ctx.fillText(mmmmmmmmmmmmmmmmmmmmmm,-300,i * 25); ctx.rotate((45 * Math.PI) / 180); // Put the watermark Adjust the deflection angle to the original, otherwise it will keep turning}
html
<canvas height=200 id=myCanvas width=200>Your browser does not support watermarks, please use Google Chrome to open it</canvas>
Let's try it now and find that there is an error.
Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
After searching Google, I found that this was caused by a cross-domain image problem. So how to solve it?
Just add an attribute to our new img.
img.setAttribute(crossorigin, crossorigin);
Therefore, the code of new img in the js part becomes
var img = new Image();// Because the business in my project is to add watermarks to Taobao pictures, so here is a main image of Taobao products img.setAttribute(crossorigin, crossorigin);// This code It is to solve the cross-domain problem. If your picture is your own and there is no cross-domain problem, you can remove img.src = 'https://gd4.alicdn.com/imgextra/i3/155/O1CN01XKkJqL1D11wYZbeI2_!!155-0-lubanu.jpg_400x400.jpg';
Next, let’s take a look at our finished product
You're done.
The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.