js實現刮刮樂抽獎效果程式碼例項

admin發表於2017-02-17

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

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html> 
<head> 
<meta charset=" utf-8"> 
<meta name="author" content="http://www.softwhy.com/" /> 
<title>螞蟻部落</title> 
<style type="text/css"> 
.mapbox{
  border:1px solid #000;
  margin:0 auto;
  width:400px;
  height:200px;
  line-height:200px;
  text-align:center;
  font-size:40px;
  color:transparent;
  position:relative;
  cursor:default
}
.mapbox canvas{
  position:absolute;
  left:0;
  top:0
}
</style> 
<script>
var loaded = function() {
  var canvas = document.getElementById("map");
  var context = canvas.getContext("2d");
  var mousedown = false;
  //底碼
  var code = Math.ceil(Math.random() * 4000);
  //繪製遮罩
  function drawMask() {
    context.save();
    context.fillStyle = "#A3A3A3";
    context.fillRect(0, 0, canvas.width, canvas.height);
    context.lineWidth = 5;
    context.strokeStyle = "#fff";
    context.strokeRect(0, 0, canvas.width, canvas.height);
    context.restore();
    context.fillStyle = "#fff";
    context.font = "italic 30px sans-serif";
    context.textBaseline = 'middle';
    context.textAlign = 'center';
    context.fillText("刮刮樂", canvas.width / 2, canvas.height / 2);
    context.restore();
  }
  //繪製塗抹
  function drawClip(x, y) {
    context.save();
    //設定組合方式
    context.globalCompositeOperation = "destination-out";
    //設定新圖形(紅色圓形)
    context.beginPath();
    context.fillStyle = "red";
    context.arc(x || canvas.width / 2, y || canvas.height / 2, 30, 0, Math.PI * 2, false);
    context.fill();
    context.restore();
  }
 
  function canvasMouseDown(event) {
    mousedown = true;
  }
 
  function canvasMouseUp(event) {
    mousedown = false;
  }
 
  function canvasMouseMove(event) {
    if (mousedown) {
      var event = event || window.event;
      drawClip(event.offsetX, event.offsetY);
    }
  }
  canvas.addEventListener("mousedown", canvasMouseDown, false);
  canvas.addEventListener("mouseup", canvasMouseUp, false);
  canvas.addEventListener("mousemove", canvasMouseMove, false);
  drawMask();
  var mapbox = document.getElementById("mapbox");
  mapbox.style.color = "#000";
  mapbox.getElementsByTagName("label")[0].innerText = "獎號:" + code;
}
window.addEventListener("load", loaded, false);
</script> 
</head>  
<body> 
<div class="mapbox" id="mapbox">
  <label></label>
  <canvas id="map" width="400" height="200"></canvas>
</div>
</body> 
</html>

相關文章