使用Canvas实现刮刮卡功能

矫情吗;* 2022-12-04 09:23 277阅读 0赞
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <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>
  9. <div class="ggk">
  10. <span></span>
  11. <canvas id="canvas">
  12. 你的浏览器版本太低, 请升级浏览器.最好使用Chrome, IE太垃圾了
  13. </canvas>
  14. </div>
  15. <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>
  16. </body>
  17. </html>

发表评论

表情:
评论列表 (有 0 条评论,277人围观)

还没有评论,来说两句吧...

相关阅读

    相关 canvas应用----

    最近在学习html5,为了更好地学习和帮助其他人我决定把我写过的案例写下来~~ 先说一下刮刮乐这个程序实现的注意点 材料:一张图片和canvas画布 在html

    相关 H5之canvas

    原理:利用globalCompositeOperation 抠出来那个画出来的那个图像设置为透明,然后就能看到这个画布下层的图片 api: globalCompositeO