<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="content" style="padding:10px;">
<h2>防删文字水印</h2>
水印内容不可删除,如检测到被删除,会重新添加水印
</div>
<script>
function add_water_canvas(){
//水印canvas
var water_canvas = document.createElement("canvas");
water_canvas.id = "water_canvas";
water_canvas.height = 100;
water_canvas.width = 300;
water_canvas.style.top = 100 + "px";
water_canvas.style.left = 100 + "px";
water_canvas.style.position = "absolute";
water_canvas.style.transform = "rotate(-45deg)";
//水印内容
var water_text = water_canvas.getContext("2d");
water_text.font = "26px 黑体";
water_text.fillText("这里是水印内容", 30, 50);
//canvas容器:水印目标
var canvas_container = document.getElementById("content");
canvas_container.style.height = 280 + "px";
canvas_container.style.width = 500 + "px";
// canvas_container.style.backgroundImage = "url(./public/forbidden.png)";
//添加水印canvas给目标div
canvas_container.appendChild(water_canvas);
}
add_water_canvas();
var observer = new MutationObserver(function(mutations){
mutations.forEach(function(mutation){
if(mutation.removedNodes.length > 0 && mutation.removedNodes[0].id == "water_canvas") {
console.log("检测到水印被删除,已重新添加水印");
//重新添加水印
add_water_canvas();
}
if (mutation.type == "attributes" && mutation.target.id == "water_canvas") {
console.log("检测到水印属性被修改,已重置属性");
water_canvas.style.display = "block";
water_canvas.style.opacity = 1;
}
});
});
observer.observe(document.body, {
childList: true,
attributes: true,
subtree: true,
attributesOldValue: true,
characterData: true,
characterDataOldValue: true,
});
</script>
</body>
</html>
标签:style,container,前端,canvas,水印,water,true
From: https://www.cnblogs.com/ExcellentDavid/p/18254472