利用canvas给网页添加文字水印

    addWaterMarker('我 是 水 印');
    function addWaterMarker(str, w=300, h=300, c='#999999') {
    // 创建一个 Canvas 元素
    var canvas = document.createElement('canvas');
    canvas.width = w; // 设置 Canvas 的宽度
    canvas.height = h; // 设置 Canvas 的高度

    // 获取 Canvas 的 2D 上下文
    var ctx = canvas.getContext('2d');

    // 设置文本样式
    ctx.font = '18px Arial';
    ctx.fillStyle = c;
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';

    // 设置字体水平度
    ctx.rotate(30 * Math.PI / 180);

    // 绘制文本
    ctx.fillText(str, canvas.width / 2, canvas.height / 2);

    // 将 Canvas 转换为 PNG 图片
    var dataURL = canvas.toDataURL('image/png');
    // 创建body下的div元素,使用固定定位,将canvas所谓背景图并铺满全屏
    let node = document.createElement("div");
    node.style.pointerEvents = "none";
    // 设置元素固定定位,并将宽高设置为100%,铺满全屏
    node.style.position = "fixed";
    node.style.width = "100%";
    node.style.height = "100%";
    node.style.top = "0";
    node.style.left = "0";
    node.style.opacity = "0.2";
    node.style.zIndex = "998";
    // 将canvas作为背景图,并设置左上开始,重复铺满全屏
    node.style.background = "url(" + dataURL + ") left top repeat";
    // 将创建的元素插入body中,作为body的子元素
    document.body.appendChild(node);
}

Tags: 前端

添加新评论