1

我是画布新手,并以示例为标题

这是我的代码:

<DOCTYPE html>
<html>
<head>
    <title>Canvas Test</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <link rel="stylesheet" type="text/css" href="style.css" />
</head>

<body>
    <form name="Show">
    X <input type="text" name="MouseX" value="0" size="4"><br>
    Y <input type="text" name="MouseY" value="0" size="4"><br>
    </form>
    <canvas id="canvas" width="300" height="300">
        Your browser does not support Canvas !!
    </canvas>

<script language="JavaScript">
    var IE = document.all?true:false;
    if (!IE) document.captureEvents(Event.MOUSEMOVE)

    document.onmousemove = getMouseXY;
    var tempX = 0;
    var tempY = 0;
    var pos= new Array();

    function getMouseXY(e) {
    if (IE) { // grab the x-y pos.s if browser is IE
    tempX = event.clientX + document.body.scrollLeft;
    tempY = event.clientY + document.body.scrollTop;
    }
    else {  // grab the x-y pos.s if browser is NS
    tempX = e.pageX;
    tempY = e.pageY;
    }  
    if (tempX < 0) {
    tempX = 0;
    }
    if (tempY < 0) {
    tempY = 0;
    }  
    document.Show.MouseX.value = tempX;
    document.Show.MouseY.value = tempY;


    pos[0]= tempX;
    pos[1]= tempY;
    return true;
    }
    $("#canvas").mousedown(function(){
    getMouseXY;
    startX= pos[0];
    startY= pos[1];
    })
    $("#canvas").mouseup(function(){
    getMouseXY;
    endX= pos[0];
    endY= pos[1];
    draw(startX, startY, endX, endY);
    })
    function draw(startX, startY, endX, endY)   {
    ctx= $("#canvas")[0].getContext('2d');

    ctx.beginPath();
    ctx.moveTo(startX, startY);
    ctx.lineTo(endX, endY);
    ctx.stroke();
    }
</script>
</body>
</html>

我的问题是:代码是wokerd,但是作为光标绘制不正确,绘制总是与光标的实际位置有距离。

那么问题是什么,请帮助我:)

4

1 回答 1

1

添加:

tempX -= $("#canvas").offset().left;
tempY -= $("#canvas").offset().top;

这是因为您的鼠标坐标是相对于窗口的,而您正在相对于画布进行绘制。

http://jsfiddle.net/75uT2/

于 2013-04-12T04:11:57.763 回答