js实现划猪
实现划猪效果的JavaScript方法
在JavaScript中实现"划猪"效果通常指模拟猪的涂鸦或绘制轨迹。以下是几种实现方式:
使用Canvas绘制轨迹
通过HTML5 Canvas可以轻松实现鼠标轨迹绘制效果:

const canvas = document.getElementById('drawingCanvas');
const ctx = canvas.getContext('2d');
let isDrawing = false;
canvas.addEventListener('mousedown', startDrawing);
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', stopDrawing);
canvas.addEventListener('mouseout', stopDrawing);
function startDrawing(e) {
isDrawing = true;
draw(e);
}
function draw(e) {
if (!isDrawing) return;
ctx.lineWidth = 5;
ctx.lineCap = 'round';
ctx.strokeStyle = '#FF69B4'; // 粉色线条
ctx.lineTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(e.clientX - canvas.offsetLeft, e.clientY - canvas.offsetTop);
}
function stopDrawing() {
isDrawing = false;
ctx.beginPath();
}
使用SVG实现动态路径
通过SVG可以创建更流畅的绘制动画:
const svg = document.getElementById('svgCanvas');
let path = null;
svg.addEventListener('mousedown', startSvgPath);
svg.addEventListener('mousemove', continueSvgPath);
svg.addEventListener('mouseup', endSvgPath);
function startSvgPath(e) {
path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
path.setAttribute('stroke', 'pink');
path.setAttribute('stroke-width', '3');
path.setAttribute('fill', 'none');
const point = getSvgPoint(e);
path.setAttribute('d', `M${point.x},${point.y}`);
svg.appendChild(path);
}
function continueSvgPath(e) {
if (!path) return;
const point = getSvgPoint(e);
const currentD = path.getAttribute('d');
path.setAttribute('d', `${currentD} L${point.x},${point.y}`);
}
function endSvgPath() {
path = null;
}
function getSvgPoint(e) {
const pt = svg.createSVGPoint();
pt.x = e.clientX;
pt.y = e.clientY;
return pt.matrixTransform(svg.getScreenCTM().inverse());
}
添加猪叫声效果
为增强体验,可以添加鼠标按下时的猪叫声:

function playOink() {
const oink = new Audio('https://www.soundjay.com/mechanical/sounds/pig-01.mp3');
oink.play();
}
// 在startDrawing或startSvgPath函数中添加
playOink();
实现橡皮擦功能
添加清除绘制的功能:
function clearCanvas() {
if (ctx) ctx.clearRect(0, 0, canvas.width, canvas.height);
if (svg) svg.innerHTML = '';
}
document.getElementById('clearBtn').addEventListener('click', clearCanvas);
移动端触摸支持
为支持触摸设备,需添加触摸事件监听:
canvas.addEventListener('touchstart', handleTouch);
canvas.addEventListener('touchmove', handleTouch);
function handleTouch(e) {
e.preventDefault();
const touch = e.touches[0];
const mouseEvent = new MouseEvent(
e.type === 'touchstart' ? 'mousedown' : 'mousemove',
{
clientX: touch.clientX,
clientY: touch.clientY
}
);
canvas.dispatchEvent(mouseEvent);
}
以上代码组合可以实现一个完整的"划猪"交互效果,包括绘制轨迹、声音反馈和清除功能。






