canvas:图像合成之刮刮乐效果实现

83 阅读1分钟

最近在重温canvas相关课程,记录一下利用canvas的图像合成实现一个刮刮乐的效果实现过程。

<html lang="en">
    <head>
        <title></title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <style>
        .wrapper { margin: 100px auto; width: 200px;  position: relative; }
        .box { position: absolute; text-align: center; width: 200px; height: 200px; background-color: antiquewhite; cursor: pointer; }
        span { font-size: 44px; line-height: 200px; }
        canvas { position: absolute; }
    </style>
    <body>
        <div class="wrapper">
            <div class="box">
                <!-- 奖项说明 -->
                <span>一等奖</span>
            </div>
        </div>
        <script>
            // 创建一个画板,盖上去
            const canvas = document.createElement('canvas');
            canvas.width = 200;
            canvas.height = 200;
            document.querySelector('.wrapper').appendChild(canvas);
            const ctx = canvas.getContext('2d');
            ctx.beginPath();
            ctx.fillStyle = '#ccc';
            ctx.fillRect(0, 0, 200, 200);
            
            // 图像合成:现有内容保持在新图形不重叠的地方
            ctx.globalCompositeOperation = 'destination-out'; 

            ctx.beginPath();
            ctx.strokeStyle = '#fff';
            ctx.lineWidth = 20;
            ctx.lineCap = 'round';
            ctx.lineJoin = 'round';
            // 鼠标按下的话就开始记录鼠标坐标为起点
            canvas.onmousedown = function(e) {
                ctx.moveTo(e.offsetX, e.offsetY);
                canvas.onmousemove = function(e) {
                    // 随着鼠标的不断移动画线条
                    ctx.lineTo(e.offsetX, e.offsetY);
                    ctx.stroke();
                }
                // 鼠标抬起或者移除画布就清空对应事件
                canvas.onmouseup = canvas.onmouseout = function (e) {
                    canvas.onmousemove = null;
                    canvas.onmouseup = null;
                    canvas.onmouseout = null;
                }
            }
        </script>
    </body>
</html>

效果

GIF 2024-02-01 14-12-15.gif