我有一个创建新图像的函数,并为它提供一个事件监听器,它需要访问一个全局变量。定义全局变量(_currentSection),直到它获得事件监听器的声明,然后变为未定义。这是功能:
function relMouseCoords(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);
for (var i = 0; i < _currentSection.allHotSpots.length; i++) {
if (canvasX > _currentSection.allHotSpots[i].topLeft[0] &&
canvasX < _currentSection.allHotSpots[i].bottomRight[0] &&
canvasY > _currentSection.allHotSpots[i].topLeft[1] &&
canvasY < _currentSection.allHotSpots[i].bottomRight[1]) {
//alert( 'x: ' + canvasX + ' y: ' + canvasY);
if (_currentSection.allHotSpots[i].isPicZoom === "false") {
appendHotSpot(_currentSection.allHotSpots[i], _currentSection.thePicture, _context, true);
} else {
picZoomCode = _currentSection.allHotSpots[i].myPicZoom;
var img = new Image();
img.onload = function() {
_context.drawImage(img, 0, 0, _canvas.width, _canvas.height);
}
img.src = "data:image/jpeg;base64," + _currentSection.allHotSpots[i].picture;
img.addEventListener('load', function() {
if (_currentSection.allHotSpots[i].allHotSpots) {
for (var j = 0; j < _currentSection.allHotSpots[i].allHotSpots.length; j++) {
appendHotSpot(_currentSection.allHotSpots[i].allHotSpots[j], _currentSection.allHotSpots[i].thePicture, _context, false)
}
}
}, false);
}
}
}
}
HTMLCanvasElement.prototype.relMouseCoords = relMouseCoords;
所以在img.addEventListener中我需要访问_currentSection,但它只是在img.addEventListener中未定义。我如何保持定义?
答案 0 :(得分:0)
尝试将变量置于var currentElement = this;
之上答案 1 :(得分:0)
我怀疑这篇文章中与第8项类似的东西: