jQuery仿橡皮擦是一种基于jQuery库实现的图像编辑功能,它允许用户在图像上像使用橡皮擦一样擦除部分图像内容。这种功能通常用于图像编辑器、在线画板等应用场景。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery橡皮擦示例</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
#canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
<script>
$(document).ready(function() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.src = 'path/to/your/image.jpg';
img.onload = function() {
ctx.drawImage(img, 0, 0);
};
var isErasing = false;
var lastX, lastY;
$('#canvas').on('mousedown', function(e) {
isErasing = true;
lastX = e.offsetX;
lastY = e.offsetY;
});
$('#canvas').on('mousemove', function(e) {
if (isErasing) {
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(e.offsetX, e.offsetY);
ctx.lineWidth = 20; // 橡皮擦大小
ctx.strokeStyle = 'white'; // 橡皮擦颜色(与背景色相同)
ctx.stroke();
lastX = e.offsetX;
lastY = e.offsetY;
}
});
$('#canvas').on('mouseup', function() {
isErasing = false;
});
});
</script>
</body>
</html>
ctx.lineWidth
和ctx.strokeStyle
的值,使其符合预期效果。通过以上介绍和示例代码,你应该能够实现一个基本的jQuery仿橡皮擦功能,并了解其相关概念、优势和应用场景。
领取专属 10元无门槛券
手把手带您无忧上云