canvas实现刮图效果
Posted 绯叶阿卡丽
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了canvas实现刮图效果相关的知识,希望对你有一定的参考价值。
<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实现刮图效果的主要内容,如果未能解决你的问题,请参考以下文章
自己定义View时,用到Paint Canvas的一些温故,简单的帧动画(动画一 ,"掏粪男孩Gif"顺便再提提onWindowFocusChanged)(代码片段