图片实现水印的方式,面试其实也是会被问到的,实现的原理就是通过canvas把图片绘制出来,同时在上面绘制出文字就可以了
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>图片水印</title>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 加载原始图片
const img = new Image();
img.src = './demo.jpg'; // 替换为你的图片路径
img.onload = () => {
// 设置画布大小
canvas.width = img.width;
canvas.height = img.height;
// 绘制原始图片
ctx.drawImage(img, 0, 0);
// 设置水印文本样式
ctx.font = '36px Arial';
ctx.fillStyle = 'rgba(255, 255, 255, 0.5)'; // 半透明白色
ctx.textAlign = 'right';
ctx.textBaseline = 'bottom';
for(let i = 0; i < 5; i++) {
// 添加水印文本
ctx.fillText('yunchong_zhao', canvas.width / 2, canvas.height - i * 150);
}
};
</script>
</body>
</html>
还是比较简单的吧 嘿嘿
关注我 持续更新前端知识