移動端利用canvas畫布簡單實現刮刮樂效果

爲了研究canvas一些屬性簡單實現的一個小效果  代碼樣式不太規範 隨手寫的 請問噴 初學者能夠看下css

css代碼

<style>
        * {
            margin: 0;
            padding: 0;
        }

        html,
        body {
            width: 100%;
            height: 100%;
        }

        .container {
            width: 100%;
            height: 100%;
            position: relative;
        }

        #box {
            width: 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>
相關文章
相關標籤/搜索