<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(); } } };
效果图: