canvas刮刮樂程式碼例項

antzone發表於2018-07-06

分享一段程式碼例項,它實現了刮刮樂效果。

用滑鼠在上面擦拭,也可以出現開獎效果,程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
.beijing {
  height: 185px;
  width: 400px;
  background-color: #c01319;
}
.zi {
  text-align: center;
}
.zi span {
  margin-top: 50px;
  font-size: 24px;
  font-family: "微軟雅黑";
  color: #c01319;
  font-weight: bold;
  padding: 20px 0;
  width: 300px;
  background-color: yellow;
  display: inline-block;
  -webkit-border-radius: 10px;
  -moz-border-radius: 10px;
  border-radius: 10px;
}
#canvas {
  position: absolute;
  top: 8px;
  left: 8px;
}
</style>
<script type="text/javascript">
window.onload = function() {
  var Zi = document.getElementById("Zi")
  var oCanvas = document.getElementById("canvas")
  var context = oCanvas.getContext("2d")
 
  //canvas上邊的佈局
  context.save();
  context.beginPath();
  context.fillStyle = "transparent";
  context.fillRect(0, 0, 400, 185);
  context.fill();
  context.closePath();
  context.restore();
  //畫畫布上的灰色遮蓋
  context.save()
  context.beginPath()
  context.fillStyle = "#c0c0c0"
  context.fillRect(50, 50, 300, 71)
  context.fill()
  context.closePath()
  context.restore()
    //當滑鼠移動時刷成透明色
  function shua() {
    document.onmousemove = function() {
      context.globalCompositeOperation = "destination-out"
      var X = event.clientX
      var Y = event.clientY
      context.save()
      context.beginPath()
      context.arc(X, Y, 25, 0, 2 * Math.PI, true)
      context.fill()
      context.closePath()
      context.restore()
    }
  }
  //背景的佈局以及文字的產生
  shua()
  huanzi()
 
  function huanzi() {
    var m = ""
    var n = Math.random()
    x = n.toFixed(1)
    console.log(x);
    if (x == 0.0 || x == 0.1) {
      m += "一等獎:100塊"
    } else if (x > 0.1 && x < 0.4) {
      m += "二等獎:10塊"
    } else if (x > 0.4 && x < 0.8) {
      m += "三等獎:5塊"
    } else if (x == 1.0) {
      m += "特等獎:我 >_<!"
    } else {
      m += "這都抽不中,手真臭"
    }
    Zi.innerText = m
  }
}
</script>
</head>
<body>
<div class="beijing">
  <div class="zi">
    <span id="Zi"></span>
  </div>
</div>
<canvas id="canvas" width="400" height="185"></canvas>
</body>
</html>

相關文章