背景文字水印效果的实现

<!doctype html>
<html lang="zh">
<head>
    <meta charset="utf-8">
    <title>背景文字水印效果的实现</title>
</head>
<body>
<style>
    * {
        margin: 0;
        padding: 0;
    }

    .container {
        position: relative;
        margin: 4vh auto 0 auto;
        width: calc(90vh * 0.618);
        height: 90vh;
        border: 1vh solid #cacdd1;
        background-repeat: repeat;
    }

    canvas {
        display: none;
    }
</style>
<div id="container" class="container"><!-- 容器 --></div>
<script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<script type="text/javascript">
    let text = '背景文字水印效果的实现';
    let fontSize = 18;

    // 获取字符串长度函数(一个中文汉字占两个字节)
    let strlen = function (str) {
        let length = 0;
        let charCode = -1;
        for (let i = 0; i < str.length; i++) {
            charCode = str.charCodeAt(i);
            if (charCode >= 0 && charCode <= 128) {
                length += 1;
            } else {
                length += 2;
            }
        }
        return length;
    }

    console.log('文字长度:' + strlen(text));

    let container = document.getElementById('container');

    // 创建canvas元素
    let canvas = document.createElement('canvas');
    // canvas.width = container.offsetWidth;
    // canvas.height = container.offsetHeight;

    // 根据水印文字的长度和字体大小算出画布的宽高
    // canvas.width = container.offsetWidth;
    // canvas.height = strlen(text) * fontSize * Math.sin(20 * 0.017453293);
    // canvas.width = Math.sqrt(Math.pow(strlen(text) * fontSize, 2) - Math.pow(canvas.height, 2));

    console.log('文字长度*字体大小:' + strlen(text) * fontSize);
    console.log('canvas宽度:' + canvas.width);
    console.log('canvas高度:' + canvas.height);

    canvas.style.top = '0';
    canvas.style.left = '0';
    canvas.style.position = 'absolute';

    container.appendChild(canvas);

    let context = canvas.getContext('2d');

    context.rotate(-20 * Math.PI / 180); // 设置水印文字的倾斜角度
    context.font = '18px "Courier New"'; // 设置水印文字的大小和字体(注:必须设置字体)
    context.fillStyle = '#10aeff'; // 设置水印文字的颜色
    context.textAlign = 'center'; // 设置水印文字的水平对齐方式
    context.textBaseline = 'middle'; // 设置水印文字的垂直对齐方式
    context.fillText(text, 120, 120);

    // 水印图片的base64编码
    let base64 = canvas.toDataURL('image/png');
    console.log(base64);

    // 将水印图片作为容器的背景图
    container.style.backgroundImage = 'url(' + base64 + ')';
</script>
</body>
</html>

Copyright © 2024 码农人生. All Rights Reserved