Sam*_*Lee 43 javascript html5 canvas
有没有办法将位置鼠标放在<canvas>标签内?我想要相对于右上角的位置<canvas>,而不是整个页面.
Jan*_*nen 41
最简单的方法可能是将一个onmousemove事件监听器添加到canvas元素,然后您可以从事件本身获取相对于画布的坐标.
如果您只需要支持特定的浏览器,这是微不足道的,但f.ex之间存在差异.Opera和Firefox.
这样的东西应该适用于这两个:
function mouseMove(e)
{
var mouseX, mouseY;
if(e.offsetX) {
mouseX = e.offsetX;
mouseY = e.offsetY;
}
else if(e.layerX) {
mouseX = e.layerX;
mouseY = e.layerY;
}
/* do something with mouseX/mouseY */
}
Run Code Online (Sandbox Code Playgroud)
小智 37
接受的答案不会每次都有效.如果不使用相对位置,则属性offsetX和offsetY可能会产生误导.
您应该使用以下函数:canvas.getBoundingClientRect()来自canvas API.
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
canvas.addEventListener('mousemove', function(evt) {
var mousePos = getMousePos(canvas, evt);
console.log('Mouse position: ' + mousePos.x + ',' + mousePos.y);
}, false);
Run Code Online (Sandbox Code Playgroud)
Sim*_*ris 16
我将分享迄今为止我创建的最防弹鼠标代码.它适用于所有浏览器将各种填充,边距,边框和附加组件(如stumbleupon顶部栏)
// Creates an object with x and y defined,
// set to the mouse position relative to the state's canvas
// If you wanna be super-correct this can be tricky,
// we have to worry about padding and borders
// takes an event and a reference to the canvas
function getMouse = function(e, canvas) {
var element = canvas, offsetX = 0, offsetY = 0, mx, my;
// Compute the total offset. It's possible to cache this if you want
if (element.offsetParent !== undefined) {
do {
offsetX += element.offsetLeft;
offsetY += element.offsetTop;
} while ((element = element.offsetParent));
}
// Add padding and border style widths to offset
// Also add the <html> offsets in case there's a position:fixed bar (like the stumbleupon bar)
// This part is not strictly necessary, it depends on your styling
offsetX += stylePaddingLeft + styleBorderLeft + htmlLeft;
offsetY += stylePaddingTop + styleBorderTop + htmlTop;
mx = e.pageX - offsetX;
my = e.pageY - offsetY;
// We return a simple javascript object with x and y defined
return {x: mx, y: my};
}
Run Code Online (Sandbox Code Playgroud)
您会注意到我使用了函数中未定义的一些(可选)变量.他们是:
stylePaddingLeft = parseInt(document.defaultView.getComputedStyle(canvas, null)['paddingLeft'], 10) || 0;
stylePaddingTop = parseInt(document.defaultView.getComputedStyle(canvas, null)['paddingTop'], 10) || 0;
styleBorderLeft = parseInt(document.defaultView.getComputedStyle(canvas, null)['borderLeftWidth'], 10) || 0;
styleBorderTop = parseInt(document.defaultView.getComputedStyle(canvas, null)['borderTopWidth'], 10) || 0;
// Some pages have fixed-position bars (like the stumbleupon bar) at the top or left of the page
// They will mess up mouse coordinates and this fixes that
var html = document.body.parentNode;
htmlTop = html.offsetTop;
htmlLeft = html.offsetLeft;
Run Code Online (Sandbox Code Playgroud)
我建议只计算一次,这就是为什么它们不在getMouse函数中.
对于鼠标位置,我通常使用jQuery,因为它规范了一些事件属性.
function getPosition(e) {
//this section is from http://www.quirksmode.org/js/events_properties.html
var targ;
if (!e)
e = window.event;
if (e.target)
targ = e.target;
else if (e.srcElement)
targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
// jQuery normalizes the pageX and pageY
// pageX,Y are the mouse positions relative to the document
// offset() returns the position of the element relative to the document
var x = e.pageX - $(targ).offset().left;
var y = e.pageY - $(targ).offset().top;
return {"x": x, "y": y};
};
// now just make sure you use this with jQuery
// obviously you can use other events other than click
$(elm).click(function(event) {
// jQuery would normalize the event
position = getPosition(event);
//now you can use the x and y positions
alert("X: " + position.x + " Y: " + position.y);
});
Run Code Online (Sandbox Code Playgroud)
这适用于所有浏览器.
编辑:
我从我正在使用的一个类中复制了代码,因此jQuery调用this.canvas是错误的.更新的函数计算出哪个DOM元素(targ)导致事件,然后使用该元素的偏移量来确定正确的位置.