<canvas id="myCanvas" width="300" height="300"></canvas>
<script>
var myCanvas = document.getElementById('myCanvas'),
ctx = myCanvas.getContext('2d'),
w = myCanvas.width,
h = myCanvas.height,//存画布宽高
lastPoint = {},//保存防断点的新坐标
nowPoint = {};//旧坐标
function init() {//函数入口
ctx.fillStyle = '#ccc';
ctx.fillRect(0, 0, w, h);//画一个涂层
ctx.globalCompositeOperation = 'destination-out';//象素合并方式
var img = new Image();
img.src = './1115.jpg';
img.onload = function () {
myCanvas.style.background = 'url('+ img.src +')';//给画布添加背景
myCanvas.addEventListener('mousedown', downFunc, false);//给当前函数绑定事件函数
}
}
init();
function downFunc(e) {//点击函数
lastPoint.x = e.clientX - myCanvas.offsetLeft;
lastPoint.y = e.clientY - myCanvas.offsetTop;//新坐标
myCanvas.addEventListener('mousemove', moveFunc, false);
document.addEventListener('mouseup', upFunc, false);//防止画布外抬起无法触发事件
}
function moveFunc(e) {//指针函数
nowPoint.x = e.clientX - myCanvas.offsetLeft,
nowPoint.y = e.clientY - myCanvas.offsetTop;//旧坐标
ctx.beginPath();//开启新路经
ctx.lineWidth = 40;
ctx.lineCap = 'round';//添加线段样式
ctx.moveTo(lastPoint.x, lastPoint.y);//新坐标
ctx.lineTo(nowPoint.x, nowPoint.y);//旧坐标
ctx.stroke();//填补事件触发产生的断点
ctx.arc(nowPoint.x, nowPoint.y, 20, 0, Math.PI*2, 0);
ctx.closePath();//闭合
ctx.fill();//触犯事件清除的范围
lastPoint.x = nowPoint.x;
lastPoint.y = nowPoint.y;//新旧交替保存
}
function upFunc() {//抬起函数
myCanvas.removeEventListener('mousemove', moveFunc, false);//都清除
document.removeEventListener('mouseup',upFunc, false);//防止画布外抬起无法触发事件
clearCanvas();//判断涂层清除到百分之七十
}
function clearCanvas() {
var d = ctx.getImageData(0,0,w,h),//获取象素
c = 0,
len = d.data.length;
for(var i = 0; i < len; i += 4) {
if(d.data[i] === 0) {//计算象素是否改变
c++;
}
}
if(c > len/4 * 0.7) {//到了百分之七十个擦除画布
ctx.clearRect(0, 0, w, h);
}
}
</script>
canvas实现刮刮乐
最新推荐文章于 2025-04-14 19:57:40 发布