javascript - 關於canvas中取得滑鼠座標的問題
过去多啦不再A梦
过去多啦不再A梦 2017-05-19 10:29:32
0
1
520

我想做一個滑鼠畫線的效果 就是類似window自帶的畫圖板那個畫線的功能。這個需要取得滑鼠的座標值,但是我總感覺座標取得得不準確,每次我在畫布上畫出線條的時候,線條總是在遊標明顯靠下的位置畫出來的,而不是從遊標的位置開始畫線的。如果在畫布的下邊畫線條 根本出不來,可能取得的實際座標值超過了畫布的大小了。難道是我取得座標值的方法不對,想請教大家!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
    <style> body {
        background: #000;
    } </style>
    <script> window.onload = function () {
        var oC = document.getElementById('cav');
        var ctx = oC.getContext('2d');
        oC.onmousedown = function (evt) {
            var x = evt.pageX - oC.offsetLeft;
            var y = evt.pageY - oC.offsetTop;
            ctx.moveTo(x, y);
            oC.onmousemove = function (evt) {
                var x = evt.pageX - oC.offsetLeft;
                var y = evt.pageY - oC.offsetTop;
                ctx.lineTo(x, y);
                ctx.stroke();
            }
            oC.onmouseup = function () {
                oC.onmousemove = null
            }
        }
    } </script>
</head>
<body>
<canvas id="cav" style="width: 400px;height: 400px;background: white"></canvas>
</body>
</html>
过去多啦不再A梦
过去多啦不再A梦

全部回覆(1)
我想大声告诉你
<canvas id="cav" style="width: 400px;height: 400px;background: white"></canvas>

換成

<canvas id="cav" width="400" height="400" style="background: white"></canvas>

canvas標籤的width和height以及style.width和style.height的區別

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!