簡體   English   中英

HTML 5 Canvas中的鼠標位置

[英]Mouse position within HTML 5 Canvas

我正在編寫一個簡單的繪圖應用程序來了解HTML 5畫布。 問題是我似乎無法在canvas元素中獲得正確的鼠標位置。我已經查看了stackoverflow上的其他問題,就像在這里用javascript在畫布獲取鼠標位置來解決這個問題,但是他們的解決方案沒有好像在幫助我。

這是我的代碼:

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
        <title>Untitled Document</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
        <style type="text/css">
            #test {
                border: solid black 1px;
                width: 500px;
                height: 500px;
            }
        </style>
        <script type="text/javascript">
            $(function(){
                var canvas=document.getElementById('test');
                if(canvas.getContext){
                    var ctx =canvas.getContext('2d');       
                    var draw = false;
                    ctx.strokeStyle = "rgb(200,0,0)";
                    ctx.lineWidth = 3;
                    ctx.lineCap = "round"; 

                    $('#test').mousedown(function(){draw=true;});
                    $('#test').mouseup(function(){draw=false;});
                    $('#test').mousemove(function(e){
                        if(draw){
                            var x , y;
                            x = e.layerX;
                            y = e.layerY;
                            ctx.moveTo(x,y);
                            ctx.lineTo(x+1,y+1);
                            ctx.stroke();
                                             }
                                    });
                }
            });
        </script>
    </head>
    <body>
        <canvas id="test"></canvas>
    </body>
</html>

我在這做錯了什么? 我在Chrome / Firefox中測試了這個。

您的畫布缺少寬度和高度屬性。 在當前的解決方案中,它只是縮放默認值以適合您的CSS。 這反過來打破了你的鼠標坐標。 嘗試一下

<canvas id="test" width=500 height=500></canvas>

作為畫布標記。

假設你的畫布已經被聲明了......

var Mouse = { //make a globally available object with x,y attributes 
    x: 0,
    y: 0
}
canvas.onmousemove = function (event) { // this  object refers to canvas object  
    Mouse = {
        x: event.pageX - this.offsetLeft,
        y: event.pageY - this.offsetTop
    }
}

鼠標在畫布上移動時鼠標將更新

您應該為canvas元素添加像素尺寸:

<canvas id="test" width='500px' height='500px' ></canvas>

這是工作示例 - http://jsfiddle.net/gorsky/GhyPr/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM