我的画布在点击时会提醒您点击的位置。这样可以正常工作,但现在我想将参数传递给函数domouseDown,同时还能够访问事件以获取点击位置(事件) .pageX)。我通过将事件Listener更改为function(){doMouseDown(param);已成功将参数传递给函数。但是,然后event.pagex和y不再有效。我需要得到两者,但我似乎只能让一个或另一个工作。
<canvas id="canvas" width="1000" height="400"></canvas>
的JavaScript
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
canvas.addEventListener("mousedown", doMouseDown, false);
//Or canvas.addEventListener("mousedown", function(){doMouseDown(param); }, false);
function doMouseDown(event) {
//or function doMouseDown(event, param){
var totalOffsetX = 0;
var totalOffsetY = 0;
var canvasX = 0;
var canvasY = 0;
var currentElement = this;
do {
totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;
totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;
}
while (currentElement = currentElement.offsetParent)
canvasX = event.pageX - totalOffsetX;
canvasY = event.pageY - totalOffsetY;
alert("x" + canvasX + " " + "y:" + canvasY);
}
答案 0 :(得分:1)
我不确定,但这需要你吗?
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
canvas.addEventListener("mousedown", createEventWithParam("MyParam"), false);
function createEventWithParam(param) {
return function doMouseDown(event){
var totalOffsetX = 0;
var totalOffsetY = 0;
var canvasX = 0;
var canvasY = 0;
var currentElement = this;
do{
totalOffsetX += currentElement.offsetLeft - currentElement.scrollLeft;
totalOffsetY += currentElement.offsetTop - currentElement.scrollTop;
}
while(currentElement = currentElement.offsetParent)
canvasX = event.pageX - totalOffsetX;
canvasY = event.pageY - totalOffsetY;
alert("x" + canvasX + " " + "y:" + canvasY + " - " + param);
}
}
这是一种使用参数创建事件处理程序的方法。