JS利用Canvas實現(xiàn)文字水印和圖片水印合成
介紹
給圖片添加水印可以幫助網(wǎng)站或作者保護自己的版權(quán),或防止內(nèi)容被別人利用。給圖片添加水印分為添加文字水印和添加圖片水印,水印一般都做成半透明的,這樣不至于影響原圖內(nèi)容的瀏覽。Canvas 圖片水印合成與 Canvas 實現(xiàn)圖片壓縮 原理基本相同:
- CanvasRenderingContext2D.drawImage(image, dx, dy, dWidth, dHeight) 方法可以從頁面 DOM 元素作為圖像源來根據(jù)坐標和大小重新繪制該圖像。
- HTMLCanvasElement.toDataURL() 方法支持導(dǎo)出為 base64 字符串。
文字水印
首先創(chuàng)建一個空的 canvas 元素,并獲取其上下文。
const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d');
獲取頁面上需要合成水印的 img 元素,或者根據(jù)一個 File 或 Blob 對象,創(chuàng)建一個空的 img 元素,將其 src 設(shè)為 File 或 Blob 對象的 URL。
設(shè)置 canvas 元素的寬高為 img 元素的寬高,清除畫布,繪制圖像。
canvas.width = img.width; canvas.height = img.height; ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
設(shè)置字體、對齊方式、旋轉(zhuǎn)角度。
ctx.font = `bold ${img.height / 10}px arial`; ctx.fillStyle = 'rgba(255, 0, 0, .2)'; ctx.textBaseline = 'bottom'; ctx.transform(1, 0.5, -0.5, 1, 0, -canvas.height / 2);
定義水印文字、水印高度,循環(huán)繪制水印。
let txt = '1234567 '; const txtHeight = img.height / 6; txt = Array(Math.ceil(canvas.width / ctx.measureText(txt).width) * 2).join(txt); for (let i = 0; i < Math.ceil(canvas.height / txtHeight) * 2; i++) { ctx.fillText(txt, 0, i * txtHeight); }
在頁面渲染合成后的圖像,釋放創(chuàng)建的 URL 對象。
result.src = canvas.toDataURL(type); URL.revokeObjectURL(img.src);
效果
圖片水印
首先創(chuàng)建一個空的 canvas 元素,并獲取其上下文。
const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d');
獲取頁面上需要合成水印的 img 元素,或者根據(jù)一個 File 或 Blob 對象,創(chuàng)建一個空的 img 元素,將其 src 設(shè)為 File 或 Blob 對象的 URL。
設(shè)置 canvas 元素的寬高為 img 元素的寬高,清除畫布,繪制圖像。
canvas.width = img.width; canvas.height = img.height; ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
設(shè)置旋轉(zhuǎn)角度,創(chuàng)建重復(fù)圖像的模式,繪制水印。
ctx.transform(1, 0.5, -0.5, 1, 0, -canvas.height / 2); ctx.rect(0, 0, canvas.width, canvas.height); ctx.fillStyle = ctx.createPattern(imgCover, 'repeat'); ctx.fill();
在頁面渲染合成后的圖像,釋放創(chuàng)建的 URL 對象。
result.src = canvas.toDataURL(type); URL.revokeObjectURL(img.src);
效果
到此這篇關(guān)于JS利用Canvas實現(xiàn)文字水印和圖片水印合成的文章就介紹到這了,更多相關(guān)JS Canvas水印內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于jQuery通過jQuery.form.js插件使用ajax提交form表單
在jQuery Form插件可以讓你很容易的使用AJAX提交Form表單,主要方法ajaxForm和ajaxSubmit負責(zé)收集表單元素的信息,管理提交進程。這兩種方法都是可配置的,讓你完全控制Form提交,本篇文章介紹基于jQuery通過jQuery.form.js插件使用ajax提交form表單,需要的朋友可以參考下2015-08-08Bootstrap Navbar Component實現(xiàn)響應(yīng)式導(dǎo)航
這篇文章主要介紹了Bootstrap Navbar Component實現(xiàn)響應(yīng)式導(dǎo)航的相關(guān)資料,講解了Bootstrap Navbar應(yīng)用及源碼解析,需要的朋友可以參考下2016-10-10通過JavaScript使Div居中并隨網(wǎng)頁大小改變而改變
自己的頁面太難看了,要居中沒居中,要顏色沒顏色,但是無論是怎么樣都得使登錄的框居中吧,下面與大家分享下通過JavaScript可以簡單的使Div在頁面上居中,隨著網(wǎng)頁大小的改變做出相應(yīng)的改變2013-06-06