I\'m very new to javascript and canvas and I have a program that\'s supposed to detect elements animated on an elliptical path. It later on goes to form a tree.. But this is
Using the transformation matrix is useful or even necessary in these circumstances:
But for the simpler case of panning and scaling the entire canvas there is a simpler method.
First, set up variables to hold the current amount of scaling and panning:
var scaleFactor=1.00;
var panX=0;
var panY=0;
Then use these pan & scale variables to do all your drawings.
panX variable.scaleFactor variable.Example code:
function drawTranslated(){
ctx.clearRect(0,0,cw,ch);
ctx.save();
ctx.translate(panX,panY);
ctx.scale(scaleFactor,scaleFactor);
ctx.beginPath();
ctx.arc(circleX,circleY,15,0,Math.PI*2);
ctx.closePath();
ctx.fillStyle=randomColor();
ctx.fill();
ctx.restore();
}
Now, about mouse coordinates:
The browser always returns the mouse position in untransformed coordinates. Your drawings have been done in transformed space. If you want to know where your mouse is in transformed space, you can convert untransformed mouse coordinates to transformed coordinates like this:
var mouseXTransformed = (mouseX-panX) / scaleFactor;
var mouseYTransformed = (mouseY-panY) / scaleFactor;
Here is example code and a Demo: http://jsfiddle.net/m1erickson/HwNp3/
Transformed coordinates are mouseXY in transformed space.
The circles center is always at translated [150,150]
Screen Coordinates:
Transformed Coordinates:
Pan & Scale