So, I am working on developing some software in HTML5, which involves the use of canvases. There is one canvas in which I should be able to scale and allow the user to draw on the canvas with mouse clicks. So far, I got scaling for the job, with some examples that I found. The problem is that after scaling, the position of the mouse in my drawing tool is out of order. Before any scaling, I can draw just fine. Here is the code to enlarge:
//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); }
As I said, scaling is not a real problem, but only the root of the problem. Here is the code that determines the mouse position for the drawing tool:
//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); } }
I'm sure the problem is in the last block of code, but I'm not sure how to fix it. Any help would be appreciated.
source share