HTML5 Canvas實現刮刮卡效果實例


HTML:

<style>
#canvas {
    border: 1px solid blue;
    position: absolute;
    left: 10px;
    top: 10px;
    background:url(../Images/1.jpg) no-repeat center center;
    background-size:contain;
}
</style>
<canvas id="canvas"></canvas>

一、解決方案1是使用clearRect清空鼠標位置的像素

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'gray';
ctx.rect(0, 0, canvas.width, canvas.height);
ctx.fill();
//解決方案1是使用clearRect清空鼠標位置的像素
var isClear = false;
//設置清空部分
canvas.onmousedown = function (ev) {
    isClear = true;
}
canvas.onmouseup = function () {
    isClear = false;
}
canvas.onmousemove = function (ev) {
    if (isClear == false)
        return;
    ev = ev || window.event;
    //清空像素,根據當前所在點
    var curX = ev.clientX - canvas.offsetLeft;
    var curY = ev.clientY - canvas.offsetTop;
    var step = 20;
    ctx.clearRect(curX - step / 2, curY - step / 2,
        step, step);
    ev.stopPropagation();
}

二、解決方案2是使用globalCompositeOperation,重疊處理,重疊的透明處理

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'gray';
ctx.rect(0, 0, canvas.width, canvas.height);
ctx.fill();

//解決方案2是使用globalCompositeOperation,重疊處理
//優點使用 fill() 不限制是否是矩形
//在與源不重疊的區域上保留目標。其他部分都變成透明的。
ctx.globalCompositeOperation = 'destination-out';
var isClear = false;
//設置清空部分
canvas.onmousedown = function (ev) {
    isClear = true;
}
canvas.onmouseup = function () {
    isClear = false;
}
canvas.onmousemove = function (ev) {
    if (isClear == false)
        return;
    ev = ev || window.event;
    //清空像素,根據當前所在點
    var curX = ev.clientX - canvas.offsetLeft;
    var curY = ev.clientY - canvas.offsetTop;
    var step = 10;
    ctx.beginPath();
    ctx.arc(curX, curY, step, 0, Math.PI * 2, false);
    ctx.fill();
    ev.stopPropagation();
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM