整体思路
1:、使用canvas绘制出水印的内容
2.、转换成base64格式的图片
3、最后给他添加到页面元素中
实现代码
function addWaterMarker(str, name, number) {
let can = document.createElement('canvas');
let body = document.body;
body.appendChild(can);
can.width = 180;
can.height = 150;
can.style.display = 'none';
let cans = can.getContext('2d');
cans.rotate(-20 * Math.PI / 180);
cans.font = "normal 12px Microsoft JhengHei";
cans.fillStyle = "rgba(223, 223, 223, 1)";
cans.textAlign = 'center';
cans.textBaseline = 'Middle';
let nameNo = name + ' ' + str;
cans.fillText(nameNo, can.width / 3, can.height / 2);
cans.fillText(number, can.width / 2.7, can.height / 1.6);
let dom = document.querySelector('.box')
dom.style.backgroundImage = "url(" + can.toDataURL("image/png") + ")";
dom.style.backgroundColor = "#fff";
}
下面我们来调用一下看看效果:
addWaterMarker('张三', 'Code12345', 1888888888)