原代碼問題
- Canvas 元素缺失(HTML 中無
<canvas>)
- 事件綁定用
mycanvas.onmousedown,但變量名為 c
- 未處理高 DPI 屏幕模糊問題
修正後完整代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Canvas 折線繪製</title>
<style>
canvas { border: 1px solid #ccc; cursor: crosshair; }
</style>
</head>
<body>
<canvas id="myCanvas" width="800" height="600"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 高 DPI 適配
const dpr = window.devicePixelRatio || 1;
canvas.width = 800 * dpr;
canvas.height = 600 * dpr;
ctx.scale(dpr, dpr);
canvas.style.width = '800px';
canvas.style.height = '600px';
ctx.strokeStyle = 'rgb(0, 182, 0)';
ctx.lineWidth = 2;
const points = [];
canvas.onmousedown = function(e) {
ctx.clearRect(0, 0, 800, 600);
const rect = canvas.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
points.push({x, y});
if (points.length === 1) {
ctx.beginPath();
ctx.moveTo(x, y);
} else {
ctx.lineTo(x, y);
ctx.stroke();
}
};
</script>
</body>
</html>
關鍵修正點
- 添加
<canvas id="myCanvas"> 元素
- 事件綁定用
canvas.onmousedown(變量名一致)
- 座標計算用
getBoundingClientRect() 精確獲取
- 首次點擊
moveTo,後續 lineTo + stroke
- 高 DPI 縮放防止模糊