原生小案例:如何使用HTML5 Canvas构建画板应用程序
<!DOCTYPE html>
<html>
<head>
<title>Simple Paint App</title>
<style>
canvas {
border: 1px solid black;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="400" height="400"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
let isDrawing = false;
let lastX = 0;
let lastY = 0;
let hue = 0;
const mobile = false;
function draw(e) {
if (!isDrawing) return;
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(e.offsetX, e.offsetY);
ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`;
ctx.lineWidth = mobile ? 20 : 10;
ctx.stroke();
lastX = e.offsetX;
lastY = e.offsetY;
hue++;
}
function startPosition(e) {
isDrawing = true;
[lastX, lastY] = [e.offsetX, e.offsetY];
}
function stopPosition() {
isDrawing = false;
}
canvas.addEventListener('mousedown', startPosition);
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', stopPosition);
canvas.addEventListener('mouseleave', stopPosition);
// Support for mobile devices
canvas.addEventListener('touchstart', e => {
mobile = true;
startPosition(e.touches[0]);
e.preventDefault();
});
canvas.addEventListener('touchmove', e => {
draw(e.touches[0]);
e.preventDefault();
});
canvas.addEventListener('touchend', stopPosition);
</script>
</body>
</html>
这段代码实现了一个简单的画板应用程序,它可以在网页上运行。用户可以使用鼠标或触摸设备在画布上绘制。代码包括了鼠标和触摸事件的监听,并且对移动设备进行了适配。
评论已关闭