刮刮乐是一种常见的交互效果,通常用于抽奖活动或者隐藏信息的展示。使用jQuery实现刮刮乐效果,主要涉及HTML、CSS和JavaScript(jQuery)三个部分。
刮刮乐效果:用户通过鼠标或触摸屏在涂层上滑动,逐渐揭示下面的内容。
以下是一个简单的基于Canvas的刮刮乐实现示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery 刮刮乐</title>
<style>
#scratchpad {
width: 300px;
height: 150px;
background-color: #ddd;
position: relative;
}
#result {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
font-size: 24px;
color: white;
opacity: 0;
transition: opacity 0.5s;
}
</style>
</head>
<body>
<div id="scratchpad">
<canvas width="300" height="150"></canvas>
<div id="result">恭喜中奖!</div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="scratch.js"></script>
</body>
</html>
$(document).ready(function() {
var canvas = $('#scratchpad canvas')[0];
var ctx = canvas.getContext('2d');
var resultDiv = $('#result');
// 绘制涂层
ctx.fillStyle = '#ddd';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 设置刮擦效果
canvas.addEventListener('mousedown', startDrawing);
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', stopDrawing);
canvas.addEventListener('touchstart', startDrawing);
canvas.addEventListener('touchmove', draw);
canvas.addEventListener('touchend', stopDrawing);
var isDrawing = false;
function startDrawing(e) {
isDrawing = true;
draw(e);
}
function draw(e) {
if (!isDrawing) return;
e.preventDefault();
var x = e.clientX - canvas.offsetLeft;
var y = e.clientY - canvas.offsetTop;
ctx.globalCompositeOperation = 'destination-out';
ctx.beginPath();
ctx.arc(x, y, 20, 0, Math.PI * 2);
ctx.fill();
if (ctx.getImageData(0, 0, canvas.width, canvas.height).data.every(function(value) { return value === 255; })) {
resultDiv.css('opacity', 1);
}
}
function stopDrawing() {
isDrawing = false;
}
});
globalCompositeOperation
设置不正确。'destination-out'
。通过以上步骤和代码示例,你可以实现一个基本的刮刮乐效果。根据具体需求,还可以进一步扩展和美化界面。
领取专属 10元无门槛券
手把手带您无忧上云