添加水印效果,重点是html5中canvas的用法

 1 <!DOCTYPE html>
 2 <html>
 3 
 4     <head>
 5         <meta http-equiv="content-type" content="text/html; charset=utf-8">
 6         <title>使用HTML5 Canvas给图片加水印效果-三体教程</title>
 7     </head>
 8 
 9     <body onload="init()" >
10         <header>HTML5 Canvas神奇的图片水印</header>
11         <section id="content">
12             <canvas height="590" width="442" id="canvas"></canvas>
13         </section>
14         <input id="text" value="www.santii.com" width="100"></input>
15         <button onclick="change()">更改水印文字</button>
16         <script>
17             var text = "www.santii.com"
18 
19             function change() {
20                 text = document.getElementById("text").value;
21                 init();
22             }
23 
24             function init() {
25                 watermark('canvas', 'img/baby_b2.jpg', text);
26             }
27 
28             function watermark(id, imgsrc, txt) {
29                 canvas = document.getElementById(id);
30                 if(canvas.getContext) {
31                     ctx = canvas.getContext('2d');
32                     var img1 = new Image();
33                     img1.src = imgsrc;
34                     img1.onload = function() {
35                         var imgWidth = img1.width;
36                         var imgHeight = img1.height;
37                         canvas.width = imgWidth;
38                         canvas.height = imgHeight;
39                         ctx.drawImage(img1, 10, 10);
40                         ctx.fillStyle = 'rgba(0, 0, 0, 0.25)';
41                         ctx.font = '30px sans-serif';
42                         ctx.fillText(txt, canvas.width - (txt.length * 15), canvas.height - 10);
43                         ctx.fillStyle = 'rgba(255, 255, 255, 0.25)';
44                         ctx.fillText(txt, canvas.width - (txt.length * 15) - 2, canvas.height - 100)
45                     }
46                 }
47             }
48         </script>
49     </body>
50 
51 </html>

 

posted @ 2018-07-19 21:49  飞舞的指尖  阅读(1402)  评论(0编辑  收藏  举报