1. 程式人生 > >canvas實現刮圖效果

canvas實現刮圖效果

move 技術 flag blog tex 保留 ast rec 效果

 <canvas id="myCanvas" width=300 height=300></canvas>

JavaScript代碼:

  var canvas = document.getElementById(‘myCanvas‘),
      ctx = canvas.getContext(‘2d‘),
      w = canvas.width,
      h = canvas.height,
      area = w * h,
      flag=false,
      l = canvas.offsetLeft;
      t = canvas.offsetTop,
ctx.fillStyle = "#ccc"; //覆蓋第一層(添加灰色塗層) ctx.fillRect(0, 0, w, h);
//添加背景 即為要刮開的圖像 canvas.style.backgroundImage = ‘url(banner.jpg)‘;
//必須添加設置 ctx.globalCompositeOperation
= ‘destination-out‘; //destination-in:新加內容保留 其他變透明;destination-out:新加內容透明,其他保留; bindEvent();
var bindEvent = function () {
//移動端 // canvas.addEventListener(
‘touchmove‘, moveFunc, false); // canvas.addEventListener(‘touchend‘, endFunc, false); //pc端 canvas.onmousedown = function (e) { flag = true; lastX = e.clientX - canvas.getBoundingClientRect().left; //
canvas裏面的坐標 lastY = e.clientY - canvas.getBoundingClientRect().top; //獲取坐標 ctx.beginPath(); ctx.arc(lastX, lastY, 15, 0, Math.PI * 2, 0); ctx.fill(); } canvas.onmouseup = function (e) { flag = false; } canvas.onmousemove = function (e) { var x = e.clientX - canvas.getBoundingClientRect().left, //當前移動後的convas內部坐標 y = e.clientY - canvas.getBoundingClientRect().top; if (flag) { ctx.arc(x, y, 15, 0, Math.PI * 2, 0); ctx.fill(); } } };

效果圖:

技術分享技術分享

canvas實現刮圖效果