本篇文章介绍的是如何实现 图片水印
和 页面水印
效果,想了解通过vue实现的话,可参考 此篇文章
页面水印代码处,有防止用户通过控制台修改标签去除水印的方法,有需要的可以参考使用
图片水印:
image.png
详细代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图片水印</title>
<style>
body {
margin: 0;
}
canvas {
display: block;
background: #ccc;
}
</style>
</head>
<body>
<div>
<canvas id="watermark"></canvas>
</div>
<script>
var canvas = document.getElementById('watermark')
canvas.width = 500
canvas.height = 400
var img = new Image();
//引入图片地址
img.src = "./img/WechatIMG1.jpeg"
img.onload = function () {
//返回一个用于在画布上绘图的环境,当前唯一的合法值是2d,二维绘图
var context = canvas.getContext("2d");
var w = canvas.width
var h = canvas.height
/**画布上绘制图像、画布或视频,
* 参数——img:规定要使用的图像、画布或视频
* sx:可选。开始剪切的 x 坐标位置
* sy:可选。开始剪切的 y 坐标位置
swidth:可选。被剪切图像的宽度。
sheight:可选。被剪切图像的高度。
x:在画布上放置图像的 x 坐标位置。
y:在画布上放置图像的 y 坐标位置。
width:可选。要使用的图像的宽度(伸展或缩小图像)。
height:可选。要使用的图像的高度(伸展或缩小图像)。**/
context.drawImage(img, 0, 0, w, h);
context.font = "20px microsoft yahei";
context.fillStyle = "red";
context.fillText("文字水印", canvas.width - 100, canvas.height - 30);
}
</script>
</body>
</html>
页面水印:
image.png
详细代码:
<!DOCTYPE html>
<html>
<style>
</style>
<body>
</body>
<script>
var canvas = document.createElement('canvas')
canvas.width = 150;
canvas.height = 120;
canvas.style.display = 'none';
var shuiyin = canvas.getContext('2d');
// 控制文字的旋转角度和上下位置
shuiyin.rotate(-20 * Math.PI / 180);
shuiyin.translate(-50, 20)
//文字颜色
shuiyin.fillStyle = "#f5f5f5";
//文字样式
shuiyin.font = "100 16px Microsoft JhengHei ";
shuiyin.fillText('谁在花里胡哨', canvas.width / 3, canvas.height / 2);
// shuiyin.fillText('简书创作者', canvas.width / 3, canvas.height / 2 + 20);
/* 新建一个用于填充canvas水印的标签,之所以没有直接在body上添加,
是因为z-index对个别内容影响,才考虑的不用body */
var watermark = document.createElement('div')
const styleStr = `
position:fixed;
top:0;
left:0;
width:100vw;
height:100vh;
z-index:99;
pointer-events:none;
background-repeat:repeat;
mix-blend-mode: multiply;
background-image:url('${canvas.toDataURL("image/png")}')`;
watermark.setAttribute('style', styleStr);
watermark.classList.add('watermark')
document.body.appendChild(watermark)
//此方法是防止用户通过控制台修改样式去除水印效果
!function preventUserRemove() {
/* MutationObserver 是一个可以监听DOM结构变化的接口。 */
const MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
if (MutationObserver) {
let mo = new MutationObserver(() => {
const wmInstance = document.querySelector('.watermark');
if ((wmInstance && wmInstance.getAttribute('style') !== styleStr) || !wmInstance) {
//如果标签在,只修改了属性,重新赋值属性
if (wmInstance) {
// 避免一直触发
// mo.disconnect();
// console.log('水印属性修改了');
wmInstance.setAttribute('style', styleStr);
} else {
//标签被移除,重新添加标签
// console.log('水印标签被移除了');
document.body.appendChild(watermark)
}
}
})
mo.observe(document.body, {
attributes: true,
subtree: true,
childList: true,
});
}
}()
</script>
</html>