前段時間作了功能模塊:用戶設置自定義勳章;javascript
實現方式:前端把用戶設置的暱稱傳到後臺,後臺根據不一樣用戶等級,使用離線合成技術合成不一樣的勳章返回到前端;html
方案算是實現了,可是有點坑就是,後臺的離線合成沒有每次百分之百成功,且生成的圖片模糊,如今暫不說這個;前端
在實現上述功能模塊的時候聯想到以前有用canvas對圖片添加水印的demo,不由翻出來看一看,也算是回顧一下知識吧。java
效果:canvas
大概思路就是,獲取一張圖片,用canvas繪製一次以後,再在繪製的圖片上繪製上水印文字,注意在本地得到的圖片要轉成64base形式《Base64編碼原理與應用》。;編碼
//html <input type="file" id="uploadFile"> <label for="uploadFile" class="upload-btn">選擇圖片</label> <p>圖片預覽</p> <img src="" alt="" class="readImg"> //js var maxFilesize = 1024*1024; //文件最大不能超過100k var watermark = 'hello world'; var uploadFileEle = document.getElementById('uploadFile'); var readImg = document.querySelector('.readImg');; var canvesSize = 300; uploadFileEle.addEventListener('change',function(event){ var reader = new FileReader(); var file = event.target.files[0] || event.dataTransfer.files[0]; if(file.size > maxFilesize){ alert('上傳的圖片不能大於1M'); return; } //base64編碼 if (file) { reader.readAsDataURL(file); } reader.addEventListener("load", function () { //readImg.src = reader.result; //合成水印 compoundImg(reader.result); }, false); },false); //合成水印 function compoundImg(url){ var canvas = document.createElement('canvas'); canvas.width = canvesSize; canvas.height = canvesSize; var context = canvas.getContext('2d'); var uploadImg = new Image(); uploadImg.src = url; uploadImg.onload = function(){ //繪製上傳的圖片 context.drawImage(uploadImg,0,0,canvesSize,canvesSize,0,0,canvesSize,canvesSize); //繪製文字水印 context.rotate(-15*Math.PI/180); context.font = "40px Arial"; context.fillStyle = "rgba(17, 17, 17, .6)"; context.textBaseline = 'Middle'; context.fillText(watermark, canvesSize/8, canvesSize/2); var imgUrl = canvas.toDataURL('image/png'); readImg.src = imgUrl; } }
若是採用前端添加水印,別人徹底能夠繞過你的水印邏輯,盜用你的資源。url