首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

HTML5 Canvas 鼠標點擊繪製折線完整修正代碼

     編輯:程式設計疑難解答

原代碼問題

  • 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>

關鍵修正點

  1. 添加 <canvas id="myCanvas"> 元素
  2. 事件綁定用 canvas.onmousedown(變量名一致)
  3. 座標計算用 getBoundingClientRect() 精確獲取
  4. 首次點擊 moveTo,後續 lineTo + stroke
  5. 高 DPI 縮放防止模糊
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved