在canvas出現以前,項目中的圖片添加水印的需求,一定是後端同窗們來處理的,可是canvas出來以後,前端終於能夠站出來講,這個需求,交給我來!壯哉我大前端~,上週的任務就是在前端處理水印的效果,這個效果最重要的邏輯其實就幾行代碼,至於如何優雅的將這些簡單的邏輯封裝成方法併入公司的前端庫,應該是一個仁者見仁智者見智的問題,在此不表。html
好了,廢話不表,開始幹活。前端
<canvas id="myCanvas" width="1000" height="500" > Your browser does not support the HTML5 canvas tag. </canvas>
var img = new Image(); img.src = './img/demo.jpg';
img.onload=function(){ var canvas=document.getElementById("myCanvas"); var ctx=canvas.getContext("2d"); ctx.drawImage(img,0,0); }
注意,調用drawImage()函數以前,請確保你的圖片已經加載ok,不然你會看到canvas是空白的,這是由於在圖片尚未絕對加載到頁面以前,你直接調用了drawImage(),而這個時候,img對象仍是空的。ajax
ctx.font="20px microsoft yahei"; ctx.fillStyle = "rgba(255,255,255,0.5)"; ctx.fillText("my images",100,100);
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <canvas id="myCanvas" width="1000" height="500" > Your browser does not support the HTML5 canvas tag. </canvas> <script> //準備img對象 var img = new Image(); img.src = './img/demo.jpg'; // 加載完成開始繪製 img.onload=function(){ //準備canvas環境 var canvas=document.getElementById("myCanvas"); var ctx=canvas.getContext("2d"); // 繪製圖片 ctx.drawImage(img,0,0); // 繪製水印 ctx.font="20px microsoft yahei"; ctx.fillStyle = "rgba(255,255,255,0.5)"; ctx.fillText("my images",100,100); } </script> </body>