我正在开发一些涉及使用画布的 HTML5 软件。有一个画布,我需要能够在其中缩放并允许用户通过鼠标单击在画布上涂鸦。到目前为止,在我找到的一些示例的帮助下,我已经开始使用缩放功能。问题是缩放后,我的绘图工具上的鼠标位置不正常。在任何缩放之前,我可以画得很好。这是缩放的代码:
//Zoom
mainCanvas.onmousewheel = function(event) {
var mousex = event.clientX - mainCanvas.offsetLeft;
var mousey = event.clientY - mainCanvas.offsetTop;
var wheel = event.wheelDelta / 120;
//n or -n
var zoom = 0;
if(wheel < 0) {
zoom = 1 / 2;
if(currentzoom == 1)
return;
} else {
mousex = event.clientX - mainCanvas.offsetLeft;
mousey = event.clientY - mainCanvas.offsetTop;
zoom = 2;
if(currentzoom == 32)
return;
}
currentzoom *= zoom;
mainContext.translate(originx, originy);
mainContext.scale(zoom, zoom);
mainContext.translate(-(mousex / scale + originx - mousex / (scale * zoom ) ), -(mousey / scale + originy - mousey / (scale * zoom ) ));
originx = (mousex / scale + originx - mousex / (scale * zoom ) );
originy = (mousey / scale + originy - mousey / (scale * zoom ) );
scale *= zoom;
draw(mainContext, gridArray);
}
就像我说的,缩放不是真正的问题,只是问题的根源。这是确定绘图工具的鼠标位置的代码:
//this function determines the mouse position relative to the canvas element
function ev_canvas(ev) {
if(ev.layerX || ev.layerX == 0) {//Firefox, IE
ev._x = ev.layerX;
ev._y = ev.layerY;
} else if(ev.offsetX || ev.offsetX == 0) {//Opera
ev._x = ev.offsetX;
ev._y = ev.offsetY;
}
var func = tool[ev.type];
if(func) {
func(ev);
}
}
我确定问题出在后面的代码块中,但我不确定是否要修复它。任何帮助,将不胜感激。