<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<style> .ggk { width: 200px; height: 100px; border: 1px solid #000; margin: 0 auto; color: red; position: relative; } .ggk span { position: absolute; width: 100%; height: 100%; text-align: center; line-height: 100px; font-size: 50px; user-select: none; } canvas { position: absolute; left: 0; top: 0; } </style>
<div class="ggk">
<span></span>
<canvas id="canvas">
你的浏览器版本太低, 请升级浏览器.最好使用Chrome, IE太垃圾了
</canvas>
</div>
<script> var canvas = document.querySelector("#canvas"); draw(); function draw(){ if (!canvas.getContext) return; canvas.width = 200; canvas.height = 100; var ctx = canvas.getContext("2d"); productResult(); drawCover(ctx); scratch(ctx); } function scratch(ctx){ /*绘制线段来实现*/ canvas.onmousedown = function (e){ var downX = e.offsetX; var downY = e.offsetY; ctx.beginPath(); ctx.globalCompositeOperation = "destination-out"; ctx.lineWidth = 10; ctx.lineCap = "round"; ctx.moveTo(downX, downY); canvas.onmousemove = function (e){ var x = e.offsetX; var y = e.offsetY; ctx.lineTo(x, y); ctx.stroke(); } } /*在路径中绘制圆弧来实现*/ /*canvas.onmousedown = function (e){ canvas.onmousemove = function (e){ var x = e.offsetX; var y = e.offsetY; ctx.beginPath(); ctx.arc(x, y, 8, 0, Math.PI * 2); ctx.globalCompositeOperation = "destination-out"; ctx.fill(); ctx.closePath(); } }*/ canvas.onmouseup = function (){ canvas.onmousemove = null; } } /*生成中奖信息*/ function productResult(){ var span = document.querySelector(".ggk span"); var arr = ["100元", "200元", "300元", "400元", "谢谢", "谢谢", "谢谢", "谢谢"]; var text = arr[randomInt(0, arr.length - 1)]; span.innerHTML = text; } /*绘制覆盖层*/ function drawCover(ctx){ ctx.save(); ctx.fillStyle = "rgb(100,100,100)"; ctx.fillRect(0, 0, 200, 100); ctx.restore(); } /** 返回随机的 [from, to] 之间的整数(包括from,也包括to) */ function randomInt(from, to){ return parseInt(Math.random() * (to - from + 1) + from); } </script>
</body>
</html>
还没有评论,来说两句吧...