网页设计html最简单水印方法,前端canvas水印快速制作(附完整代码)
兩種水印效果如圖:
原理解析:
圖一斜紋類:創建一個和頁面一樣大的畫布,根據頁面大小以及傾斜角度大致鋪滿水印文字,最后轉化為一張圖片設為背景
圖二傾斜類:將文字傾斜后轉化為圖片,然后設置背景圖片repeat填充整個頁面
代碼分析:
這里我只簡略分析圖一斜紋類,事實上這兩種方式都較為簡單,不需要特別強的canvas基礎,只需大概了解就行,直接上完整代碼吧
圖一
Document.water {
width: 100vw;
height: 2000px;
position: absolute;
top: 0;
left: 0;
background-repeat: no-repeat;
}
.content {
width: 800px;
height: 2000px;
margin-left: auto;
margin-right: auto;
background: cadetblue;
overflow: hidden;
}
function addWaterMarker(str) {
// 這里限制了不超過15個字,實際按需求來
var cpyName = str;
if (str.length > 16) {
cpyName = str.substring(0, 16);
}
// 創建 canvas 元素
var can = document.createElement('canvas');
// 獲取 content 元素
var report = $('.content')[0]
// 將 canvas 元素添加到 content 中
report.appendChild(can);
// 設置 canvas頁面寬度,這里的 800 是因為我司水印文件大小固定,可按需求更改
can.width = 800;
// 獲取整個body高度
can.height = document.body.offsetHeight;
// 隱藏 canvas 元素
can.style.display = 'none';
can.style.zIndex = '999'
// 獲取 canvas 元素工具箱
var cans = can.getContext('2d');
// 設置文字傾斜角度為 -25 度以及樣式
cans.rotate(-25 * Math.PI / 180);
cans.font = "800 30px Microsoft JhengHei";
cans.fillStyle = "#000";
cans.textAlign = 'center';
cans.textBaseline = 'Middle';
// 動態改變字體大小
if(cans.measureText(cpyName).width > 180) {
var size = 180 / cpyName.length
cans.font = '800 ' + size +'px '+ ' Microsoft JhengHei'
}
/*
雙重遍歷,
當 寬度小于頁面寬度時,
當 高度小于頁面高度時,
這里的寬高可以適當寫大,目的是為了讓水印文字鋪滿
*/
for(let i = (document.body.offsetHeight*0.5)*-1; i<800; i+=160) {
for(let j = 0; j
// 填充文字,x 間距, y 間距
cans.fillText(cpyName, i, j)
}
}
// 將 canvas 轉化為圖片并且設置為背景
report.style.backgroundImage = "url(" + can.toDataURL("image/png") + ")";
}
addWaterMarker('測試水印');
圖二
Document.water {
width: 100vw;
height: 2000px;
position: absolute;
top: 0;
left: 0;
background-repeat: no-repeat;
}
.content {
width: 800px;
height: 2000px;
margin-left: auto;
margin-right: auto;
background: cadetblue;
overflow: hidden;
}
// 添加水印方法
function addWaterMarker(str) {
var cpyName = str;
if (str.length > 16) {
cpyName = str.substring(0, 16);
}
var can = document.createElement('canvas');
var report = $('.content')[0];
report.appendChild(can);
can.width = 180;
can.height = 110;
can.style.display = 'none';
can.style.zIndex = '999'
var cans = can.getContext('2d');
cans.rotate(-25 * Math.PI / 180);
cans.font = "800 30px Microsoft JhengHei";
cans.fillStyle = "#000";
cans.textAlign = 'center';
cans.textBaseline = 'Middle';
if(cans.measureText(cpyName).width > 180) {
var size = 180 / cpyName.length
cans.font = '800 ' + size +'px '+ ' Microsoft JhengHei'
}
cans.fillText(cpyName, 60, 100);
report.style.backgroundImage = "url(" + can.toDataURL("image/png") + ")";
}
addWaterMarker('測試水印');
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持。
總結
以上是生活随笔為你收集整理的网页设计html最简单水印方法,前端canvas水印快速制作(附完整代码)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 风之大陆圣痕选择是什么
- 下一篇: HTML变列自适应布局三行,CSS三行三