前端实现页面通过canvas添加全屏水印
在前端开发中,有时我们需要在页面上添加水印,以保护内容的版权或者提醒用户。本文将介绍一种通过canvas实现在页面上添加全屏水印的方法。
实现思路
我们可以通过以下步骤来实现全屏水印的效果:
- 创建一个canvas元素,并设置宽高和样式。
- 获取canvas的2D上下文。
- 通过rotate方法旋转画布,使水印倾斜。
- 设置字体、颜色、对齐方式等样式。
- 使用fillText方法在画布上绘制水印文字。
- 将canvas转换为base64格式的图片,并将其设置为页面的背景图片。
代码实现
复制代码function addWaterMarker(str) { var can = document.createElement('canvas'); var body = document.getElementById("app"); body.appendChild(can); can.width = 200; can.height = 150; can.style.display = 'none'; var cans = can.getContext('2d'); cans.rotate(-20 * Math.PI / 180); cans.font = "16px Microsoft JhengHei"; cans.fillStyle = "rgba(17, 17, 17, 0.30)"; cans.textAlign = 'left'; cans.textBaseline = 'Middle'; cans.fillText(str, can.width / 6, can.height / 2); body.style.backgroundImage = "url(" + can.toDataURL("image/png") + ")";}// 在页面加载完成后调用addWaterMarker方法,传入自定义的水印文字window.onload = function() { addWaterMarker('张健振 测试中');}使用方法
- 将以上代码复制到你的项目中。
- 将代码中的
app替换为你实际的页面容器元素的ID。 - 调用addWaterMarker方法,并传入自定义的水印文字。
复制代码addWaterMarker('这是我的水印');注意事项
- 请确保在页面加载完成后再调用addWaterMarker方法,以避免出现元素未加载完成的问题。
- 你可以根据需求调整canvas的宽高、字体大小、颜色等样式,以及水印的内容。
总结
通过canvas在页面上添加全屏水印是一种简单而有效的方式,可以用于保护内容版权或提醒用户。通过本文介绍的方法,你可以轻松地在前端项目中实现这一功能。
Disclaimers:The materials on this website are collected and sorted from the Internet. The copyright of the works belongs to the author. If it infringes your copyright, please send an email to us

简体中文
English
Article comments