canvas實現的刮刮樂程式碼例項

admin發表於2017-02-17
分享一段程式碼例項,它利用canvas實現了刮刮樂效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
.demo {
  width: 320px;
  margin: 100px auto;
}
</style>
</head>
<body>
<div class="main">
  <div class="demo">
    <canvas></canvas>
  </div>
</div>
<script>
var image = new Image();
var canvas = document.querySelector("canvas");
 
var images = ["demo/js/img/huigu.jpg", "demo/js/img/zhuomian.jpg"];
var num = Math.floor(Math.random() * images.length);
 
image.src = images[num];
 
image.addEventListener("load", function(e) { //在移動端上必須用DOM2級事件,才能用滑鼠等事件
  var ctx;
  var w = image.width;
  var h = image.height;
  var offsetX = canvas.offsetLeft; //獲取畫布在瀏覽器視口的偏移量
  var offsetY = canvas.offsetTop;
  var flag = false;
 
  function eventDown() {
    e.preventDefault(); //阻止滑鼠預設事件
    flag = true;
  }
 
  function eventUp() {
    e.preventDefault();
    flag = false;
  }
 
  function layout(ctx) {
    ctx.fillStyle = "gray"; //在畫布上加上一個圖層,用來遮蓋
    ctx.fillRect(0, 0, w, h);
  }
 
  function eventMove(e) {
    e.preventDefault();
    if (flag) {
      if (e.changedTouches) { //獲取手勢操作物件
        e = e.changedTouches[e.changedTouches.length - 1];
      }
      var x = (e.clientX + document.body.scrollLeft || e.pageX) - offsetX;
      var y = (e.clientY + document.body.scrollTop || e.pageY) - offsetY;
      with(ctx) { //判斷當前物件
        beginPath();
        arc(x, y, 30, 0, Math.PI * 2);
        fill();
      }
    }
  }
 
  canvas.width = w;
  canvas.height = h;
  canvas.style.backgroundImage = "url(" + image.src + ")";
 
  ctx = canvas.getContext("2d");
  ctx.fillRect(0, 0, w, h);
  layout(ctx);
 
  ctx.globalCompositeOperation = "destination-out"; //遮蓋行為
 
  //pc端
  canvas.addEventListener("mousedown", eventDown);
  canvas.addEventListener("mouseup", eventUp);
  canvas.addEventListener("mousemove", eventMove);
  //移動端
  canvas.addEventListener("touchstart", eventDown);
  canvas.addEventListener("touchend", eventUp);
  canvas.addEventListener("touchmove", eventMove);
})
</script>
</body>
</html>

相關文章