我正在参加「创意开发 投稿大赛」详情请看:掘金创意开发大赛来了!
平时浏览一些购物网站常常有一些抽奖的环节它们就会使用一种刮刮乐的形式给用户发一些优惠券或者其它的一些奖品。
今天我们就来简单实现一下。
页面的基本结构
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#main {
width: 1000px;
margin: 0 auto;
position: relative;
overflow: hidden;
height: 630px;
border: 2px solid #fff;
user-select: none;
}
#image {
display: block;
width: 100%;
position: absolute;
z-index: 0;
filter: blur(20px);
}
#canvas {
display: block;
position: absolute;
}
#main a {
display: block;
width: 80px;
height: 40px;
text-align: center;
line-height: 40px;
border-radius: 5px;
background: #eee;
position: absolute;
bottom: 20px;
text-decoration: none;
color: black;
z-index: 2;
}
#main a:nth-of-type(1) {
background: #eee;
right: 20px;
}
</style>
</head>
<body>
<div id="main">
<img src="https://cdn.pixabay.com/photo/2017/10/12/20/15/photoshop-2845779_1280.jpg" id="image" />
<canvas id="canvas"></canvas>
<a href="javascript:show();">显示</a>
</div>
</body>
</html>
(图片我就随便找了一个,大家用的时候,进行替换吧)
点击按钮的时候,开始画圆,填充的部分是和底部一样的图片。这样就可以给人一种擦除的感觉。
let canvasWidth = 1000;
let canvasHeight = 630;
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
canvas.width = canvasWidth;
canvas.height = canvasHeight;
let radius = 50;
let image = new Image();
image.src = "https://cdn.pixabay.com/photo/2017/10/12/20/15/photoshop-2845779_1280.jpg";
function drawClip(x, y, r) {
ctx.save();
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI * 2, false);
ctx.clip();
ctx.drawImage(image, 0, 0, canvasWidth, canvasHeight);
ctx.restore();
}
function show() {
drawClip(canvasWidth / 2, canvasHeight / 2, radius);
}
不断扩大 radius 的数值
function show() {
let time = null
clearInterval(time)
time = setInterval(() => {
radius += 10
if (radius > canvasHeight) {
clearInterval(time)
}
drawClip(canvasWidth / 2, canvasHeight / 2, radius);
}, 30);
}
是不是相当完美
监听鼠标的 mousemove 事件
image.onload = function () {
canvas.addEventListener("mousemove", drawCircle, false)
}
function drawCircle(e) {
let x = e.clientX - canvas.getBoundingClientRect().left
let y = e.clientY - canvas.getBoundingClientRect().top
if (radius < canvasHeight) {
drawClip(x, y, radius)
}
}
当鼠标按下的时候,进行擦除动作,不按压动作时,不进行擦除动作。监听 mousedown 事件,使用 onOff 变量进行控制(相当于一个开关吧)
image.onload = function () {
// ...
canvas.addEventListener("mousedown", moveDown, false);
canvas.addEventListener("mouseup", moveUp, false);
canvas.addEventListener("mouseout", moveUp, false);
}
function moveDown() {
onOff = true;
if (radius < canvasHeight) {
drawCircle();
}
}
function moveUp() {
onOff = false;
}
这就完美了。✌️
代码地址: