1. 刮刮卡
(() => {
canvas = document.createElement('canvas');
canvas.width = 700;
canvas.height = 400;
document.body.appendChild(canvas);
const cxt = canvas.getContext('2d');
canvas.style.background = 'url(https://imzbf.github.io/md-editor-v3/imgs/preview-light.png)';
canvas.style.backgroundSize = '100% 100%';
// 绘制灰色蒙板
cxt.fillStyle = 'gray';
cxt.fillRect(0, 0, canvas.width, canvas.height);
// 设置为之后绘图不显示图,并且擦掉之前的这部分图
cxt.globalCompositeOperation = 'destination-out';
const state = {
mousedown: false,
};
document.addEventListener('mousedown', () => {
state.mousedown = true;
});
document.addEventListener('mouseup', () => {
state.mousedown = false;
});
document.addEventListener('mousemove', (e) => {
if (state.mousedown) {
cxt.beginPath();
// x,y,半径,圆开始弧度,结束弧度(1倍PI是半圆)
cxt.arc(e.pageX - canvas.offsetLeft, e.pageY - canvas.offsetTop, 20, 0, 2 * Math.PI);
cxt.fill();
cxt.closePath();
}
});
})();
2. 签名
(() => {
canvas = document.createElement('canvas');
canvas.width = 700;
canvas.height = 400;
document.body.appendChild(canvas);
const cxt = canvas.getContext('2d');
// 绘制灰色蒙板
cxt.fillStyle = 'gray';
cxt.fillRect(0, 0, canvas.width, canvas.height);
document.addEventListener('mousedown', (ed) => {
cxt.moveTo(ed.pageX - canvas.offsetLeft, ed.pageY - canvas.offsetTop);
document.onmousemove = (e) => {
cxt.lineTo(e.pageX - canvas.offsetLeft, e.pageY - canvas.offsetTop);
cxt.strokeStyle = 'red';
cxt.stroke();
};
});
document.addEventListener('mouseup', () => {
document.onmousemove = () => {};
});
})();