图片实现水印的方式,面试其实也是会被问到的,实现的原理就是通过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>
还是比较简单的吧 嘿嘿
关注我 持续更新前端知识