css,js,canvas3种图片防盗

49 阅读1分钟
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Breathing Light Title</title>
</head>
<style>
    html,
    body {
        margin: 0;
        padding: 0;
        width: 100%;
        height: 100%;
    }

    @keyframes breathe {
        0% {
            opacity: 0.5;
            transform: scale(1);
        }

        50% {
            opacity: 1;
            transform: scale(1.2);
        }

        100% {
            opacity: 0.5;
            transform: scale(1);
        }
    }

    .Box {
        width: 100%;
        height: 600px;
        display: flex;
        flex-direction: column;
        justify-content: space-evenly;
        align-items: center;

    }

    .title {
        font-size: 20px;
        font-weight: 600;
        animation: breathe 3s infinite;
    }

    .img {
        width: 200px;
        height: auto;
        /*使用 CSS 属性 pointer-events: none 来禁用右键菜单。 防止右键下载 */
        /* pointer-events: none; */
        animation: breathe 3s infinite;
    }
    .canvas{
        animation: breathe 3s infinite;
    }
</style>

<body>
    <div class="Box">
        <div class="title">Welcome to Our Website</div>
        <div><img
                src="https://p6-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/063dfaef6f00421dadd3408b01dfc84d~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAgd2ViX19f:q75.awebp?rk3s=f64ab15b&x-expires=1770701689&x-signature=Q3DwlOtEaDgySPQXrUxPF8cXXQU%3D"
                alt="Example Image" class="img">
        </div>

        <canvas id="myCanvas" width="300" height="250" class="canvas"></canvas>
    </div>
</body>
<script>
    //使用 JavaScript 事件监听器来阻止右键菜单弹出。 禁止右键 事件
    document.addEventListener('contextmenu', function (e) {
        console.log(e);
        if (e.target.tagName === 'IMG') {
            e.preventDefault();
        }
    });
</script>
<script>
    // 给图片添加水印
    const canvas = document.getElementById('myCanvas');
    const ctx = canvas.getContext('2d');
    const img = new Image();
  
    img.src = 'https://p6-xtjj-sign.byteimg.com/tos-cn-i-73owjymdk6/063dfaef6f00421dadd3408b01dfc84d~tplv-73owjymdk6-jj-mark-v1:0:0:0:0:5o6Y6YeR5oqA5pyv56S-5Yy6IEAg5aSn5rygX3czY3BsdXNjb20=:q75.awebp?rk3s=f64ab15b&x-expires=1726542859&x-signature=lqcpG2vjtWNllU%2F9mVZhtDiBBMw%3D';
    img.onload = function() {
        const imgWidth = 300; // Set the width of the image
        const imgHeight = img.height * (imgWidth / img.width); // Calculate the height to maintain aspect ratio

        ctx.drawImage(img, 0, 0,imgWidth,imgHeight);
        ctx.font = '30px Arial';
        ctx.fillStyle = 'red';
        ctx.fillText('Watermark', 10, 50);
    };
  </script>

</html>