修改您的JS代码:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
$results=$("#results");
$dotposition=$("#dotposition");
var position = {x: 0, y: 0};
function handleMouseMove(e) {
e.preventDefault();
e.stopPropagation();
// You could calc the offsets once if you know
// the user will not scroll the canvas
var BB=canvas.getBoundingClientRect();
var offsetX=BB.left;
var offsetY=BB.top;
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
$results.text("Mouse position: "+mouseX+"/"+mouseY);
position.x = mouseX;
position.y = mouseY;
}
function handleMouseClick(e) {
//Clearing the canvas before redraw, remove this line if you want to keep prev images
ctx.clearRect (0 , 0 , canvas.width , canvas.height);
ctx.drawImage(img,position.x - img.width/2,position.y - img.height/2);
$dotposition.text("Dot position: "+position.x+"/"+position.y);
}
var img = new Image();
img.onload = function(){
canvas.onmousemove = handleMouseMove;
canvas.onclick = handleMouseClick;
};
img.src="https://dl.dropboxusercontent.com/s/7vlxwy1156wnhcw/redFood.png";
http://jsfiddle.net/ZH4KW/1/