我正在编写一个简单的绘图应用程序来了解
HTML 5画布.问题是,我似乎无法在canvas元素中获得正确的鼠标位置.我已经查看了stackoverflow上的其他问题,就像这里解决这个问题的
getting mouse position with javascript within canvas一样,但他们的解决方案似乎没有帮助我.
这是我的代码:
Untitled Document#test {
border: solid black 1px;
width: 500px;
height: 500px;
}
$(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();
}
});
}
});
我在这做错了什么?我在Chrome / Firefox中测试了这个.