为了研究canvas一些属性简单实现的一个小效果 代码样式不太规范 随手写的 请问喷 初学者可以看下
css代码
<style>
        * {
            margin: 0;
            padding: 0;
        }
        html,
        body {
             100%;
            height: 100%;
        }
        .container {
             100%;
            height: 100%;
            position: relative;
        }
        #box {
             100%;
            height: 300px;
            text-align: center;
            line-height: 300px;
            font-size: 30px;
            color: mediumspringgreen;
            font-weight: 900;
            background: url('https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=4210473879,3554842544&fm=27&gp=0.jpg') no-repeat;
            background-size: 100% 100%;
        }
        canvas {
            position: absolute;
            left: 0;
            top: 0;
        }
</style>
HTML代码
1 <div class="container" id="container"> 2 3 <div id="box"></div> 4 <canvas id="canvas"></canvas> 5 </div>
JS代码
1 <script> 2 canvas.width = box.offsetWidth; 3 canvas.height = box.offsetHeight; 4 let context = canvas.getContext('2d'); 5 //背景填充色 6 context.fillStyle = '#ccc'; 7 context.fillRect(0, 0, box.offsetWidth, box.offsetHeight); 8 9 //把灰色矩形当做目标对象 然后线当做源对象 10 //destination-out 在源图像外显示目标图像。只有源图像外的目标图像部分会被显示,源图像是透明的。 11 //destination-in 在源图像中显示目标图像。只有源图像内的目标图像部分会被显示,源图像是透明的。 12 context.globalCompositeOperation = 'destination-out'; 13 14 15 let arr = ["一等奖", "二等奖", "三等奖", "谢谢惠顾"]; 16 17 box.innerText = arr[Math.floor(Math.random() * arr.length)] 18 19 20 canvas.addEventListener("touchstart", function (e) { 21 context.beginPath(); 22 context.moveTo(e.touches[0].pageX, e.touches[0].pageY); 23 context.lineWidth = 20; 24 25 context.lineCap = 'round'; 26 context.lineJoin = 'round'; 27 canvas.addEventListener("touchmove", function (e) { 28 context.lineTo(e.touches[0].pageX, e.touches[0].pageY); 29 context.stroke(); 30 }) 31 canvas.addEventListener("touchend", function (e) { 32 context.closePath(); 33 34 }) 35 }) 36 </script>