我正在学习jQuery和HTML5画布。我想要做一个简单的HTML5绘图例子,当鼠标移动时,在我的鼠标下方绘制红色正方形。
我的代码很简单,但是我在获取画布内鼠标光标位置时遇到了问题。现在,我使用x = event.offsetX; 来获取鼠标位置。这在Chrome中非常有效,但是在Firefox中不起作用。我将代码更改为x = event.layerX。但似乎layerX是相对于网页而不是画布的鼠标位置,因此我总是看到一个偏移量。
我有两个问题:第一,如何在Firefox下获取正确的鼠标位置?第二,如何编写可以在IE、Firefox、Chrome、Safari和Opera上运行的代码?
这是我的代码:
<!doctype html />
<html><head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(
function(){
var flip = document.getElementById('flip');
var context = flip.getContext('2d');
context.fillStyle = "rgb(255,255,255)";
context.fillRect(0, 0, 500, 500);
$("a").click(function(event){alert("Thanks for visiting!");});
$("#flip").mousemove(function(event){
var x, y;
x = event.layerX;
y = event.layerY;
//alert("mouse pos"+event.layerX );
var flip = document.getElementById('flip');
var context = flip.getContext('2d');
context.fillStyle = "rgb(255,0,0)";
context.fillRect(x, y, 5, 5);
}
);
}
);
</script>
</head> <body bgcolor="#000000"> <a href="http://jquery.com/">jQuery</a><canvas id="flip" width="500" height="500">
This text is displayed if your browser does not support HTML5 Canvas.</canvas> </body></html>
<!doctype html />
是无效的,会触发怪异模式(quirks mode),这会改变很多 DOM 行为!正确的 DTD 是<!doctype html>
。 - Delan Azabani