HTML 5画布中的鼠标位置 [英] Mouse position within HTML 5 Canvas

查看:194
本文介绍了HTML 5画布中的鼠标位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个简单的绘图应用程序来了解HTML 5画布。问题是,我根本不能在canvas元素中获得正确的鼠标位置。我看过其他问题在stackoverflow像这里在canvas中获取鼠标位置的javascript。解决这个问题,但他们的解决方案似乎不帮助我。

I am writing a simple drawing app to get an understanding of the HTML 5 canvas. The problem is that I simply can't seem to get the correct mouse position within the canvas element.I've looked at the other questions on stackoverflow like the one here getting mouse position with javascript within canvas. that address this issue but their solutions don't seem to help me.

这是我的代码:

<!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。

What am I doing wrong here? I have tested this in both Chrome/Firefox.

推荐答案

您的画布缺少宽度和高度属性。在当前的解决方案,它只是缩放默认,以适应你的CSS。这反过来打破你的鼠标坐标。尝试

Your canvas is missing width and height properties. In the current solution it just scales the default to fit your CSS. This in turn breaks your mouse coords. Try something along

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

作为画布标记。

这篇关于HTML 5画布中的鼠标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆