How to use canvas to tile watermark for pictures
This article mainly explains "how to use canvas to tile watermark pictures", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "how to use canvas to tile watermarks pictures" bar!
The first thing that comes to mind is to use canvas to complete this function, because I have not been in contact with canvas before, so when I do this function, I am learning step by step, and the process is still quite nice. Next, follow me step by step to achieve this function and find some canvas pits.
Because all this function requires is some canvas-based api, and it does not involve any fundamental issues, here I will directly post the js code:
Var img = new Image (); / / because the business in my project is to add watermarks to the pictures of Taobao, here I put a main picture of Taobao goods 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 picture on canvas ctx.drawImage (img, 0L0200200); / / draw the watermark on canvas for (let I = 0; I < 20; iTunes +) {ctx.rotate ((- 45 * Math.PI) / 180); / / the initial deflection angle of the watermark ctx.font = "20px microsoft yahei"; ctx.fillStyle = "rgba" Ctx.fillText ("mmmmmmmmmmmmmmmmmmmmmmm",-300 I * 25); ctx.rotate ((45 * Math.PI) / 180); / / adjust the watermark deflection angle to the original, otherwise he will keep turning}
Html:
Your browser does not support watermarks, please open it with Google browser
I came to try it at this time, only to find that there was a mistake.
Failed to execute 'toDataURL' on' HTMLCanvasElement': Tainted canvases may not be exported.
After Google, it is found that this is caused by the cross-domain problem of pictures, so how to solve it?
Just add an attribute to our img from new.
Img.setAttribute ("crossorigin", "crossorigin")
As a result, the code for part of the new img in js becomes.
Var img = new Image (); / / because the business in my project is to add watermarks to the pictures of Taobao, here I put a main picture of Taobao goods img.setAttribute ("crossorigin", "crossorigin") / / this code is to solve the cross-domain problem. If your picture is your own, if 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';. Thank you for your reading, the above is the content of "how to use canvas to tile watermarks for pictures". After the study of this article, I believe you have a deeper understanding of how to use canvas to tile watermarks for pictures. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!