canvas实现图片添加水印效果HTML5
时间:6年前 阅读:4942
利用canvas可以实现向图片添加水印的功能,先通过file控件的reader选择图片,然后使用canvas添加图片及水印,并且使用toDataURL()和a标签实现添加水印后的图片的下载功能
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <canvas id="drawing" style="width:300px;border:1px solid black"> <p>The canvas element is not supported!</p> </canvas> <div> <span> <input type="file" id="addImgHelper" style="display:none"> <button id="addImg">选择图片</button> </span> <span> <button id="addWaterMark" disabled>添加水印</button> <span>水印文字为</span> <input id="waterMarkWords" type="text" value="期权记"> </span> <span> <button id="downloadImg" disabled>下载图片</button> <a id="downloadImgHelper" href="#" download="带水印图片" style="display:none"></a> </span> </div> </body> <script type="text/javascript"> if(drawing.getContext){ var cxt = drawing.getContext('2d'); var W,H; addImg.onclick = function(){ addImgHelper.click(); } addImgHelper.onchange = function(){ addWaterMark.disabled = true; downloadImg.disabled = true; var file = addImgHelper.files[0]; if(file && /image/.test(file.type)){ var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function(){ var img = new Image(); img.src= reader.result; img.onload = function(){ addWaterMark.disabled = false; drawing.width = W = img.width; drawing.height = H = img.height; cxt.drawImage(img,0,0); addWaterMark.onclick = function(){ downloadImg.disabled = false; cxt.clearRect(0,0,W,H); cxt.drawImage(img,0,0); var str = waterMarkWords.value; cxt.font = "bold 50px Arial"; cxt.lineWidth = '1'; cxt.fillStyle = 'rgba(255,255,255,0.5)'; cxt.textBaseline = "bottom"; cxt.textAlign = 'end'; cxt.fillText(str,W-10,H-10,W/2); downloadImg.onclick = function(){ downloadImgHelper.href = drawing.toDataURL('image/png'); downloadImgHelper.click(); } } } } } } } </script> </html>
本站声明:网站内容来源于网络,如有侵权,请联系我们https://www.qiquanji.com,我们将及时处理。
微信扫码关注
更新实时通知
网友评论