Canvas标签在我的页面上移动

时间:2012-01-12 00:00:23

标签: javascript html html5 html5-canvas

我正在尝试简单地在画布标签上跟踪鼠标,并记录距离圆心的距离。问题是,它略有偏差。

当我在圆圈的右侧时,鼠标必须在圆圈内约1厘米才能显示距离r(半径= 200)。当我在圆圈的左侧时,我必须在圆圈外约1厘米处记录r的距离。这就像圆圈向右移动一点。

我尝试用a fiddle复制这个,但奇怪的是,小提琴是完美的;它是现场。

所以我猜我的问题是,什么会导致我的画布标签在我的页面上移动约1厘米(但不是在小提琴上)。我需要更好的DOCTYPE吗?我在下面重现了我的整个来源。我已经在FF和Chrome测试过相同的结果。

修改

我也试过<!DOCTYPE html>无济于事。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

    <script type="text/javascript">

        $(function () {

            var context = document.getElementById("myCanvas").getContext("2d");

            context.beginPath();
            context.moveTo(250, 250);
            context.arc(250, 250, 200, 0, Math.PI * 2, false);
            context.closePath();
            context.fillStyle = 'rgb(255,100,0)';
            context.fill();


            $("canvas").mousemove(function (e) {
                var x = e.pageX;
                var y = e.pageY;

                var dist = Math.round(Math.sqrt(Math.pow(x - 250.0, 2) + Math.pow(y - 250.0, 2)));

                console.log(dist);
            });
        });


    </script>


</head>
<body>

    <canvas id="myCanvas" width="800" height="800">

    </canvas>

</body>
</html>

1 个答案:

答案 0 :(得分:1)

是的,实际上似乎body{margin:0, padding:0, border:0}可以解决问题。 另外,在旁注中,不是调用所有这些数学函数,而是更简单,更快速:

var x = e.pageX - 250;
var y = e.pageY - 250;
var dist = Math.round(Math.sqrt(x * x + y * y));

此外,使用css reset kit可能会解决所有浏览器的所有问题。

我很好奇,所以我检查了默认值:

var bodyElement = $('body');

// Get the padding
var widthPadding = bodyElement.css('padding-left') + bodyElement.css('padding-right');
var heightPadding = bodyElement.css('padding-top') + bodyElement.css('padding-bottom');
console.log(widthPadding + ", "+ heightPadding);
// Get the margins
var widthMargin = bodyElement.css('margin-left') + bodyElement.css('margin-right');
var heightMargin = bodyElement.css('margin-top') + bodyElement.css('margin-bottom');
console.log(widthMargin + ", "+ heightMargin);
// Get the borders
var widthBorder = bodyElement.css('border-left-width') + bodyElement.css('border-right-width');
var heightBorder = bodyElement.css('border-top-width') + bodyElement.css('border-bottom-width');
console.log(widthBorder + ", "+ heightBorder);

FF 9.0.1上的输出是这样的:

0px0px, 0px0px 
8px8px, 8px8px <-- So obviously you only need to reset the margins to 0
0px0px, 0px0px