Skip to content Skip to sidebar Skip to footer

How Can We Zoom In And Out Of The Graph In Html5 And Javascript?

I want to achieve the zoom feature in graph as it is there in google maps i.e. I want the graph to be zoomed along with its scale on mouse wheel event based on the mouse pointer po

Solution 1:

In order to do this, you'll have to have an offset and a zoom scale. Then, whenever you draw, you'll have to transform your drawing appropriately. Canvas makes this easy:

ctx.save();
ctx.translate(offset.x, offset.y);
ctx.scale(scale, scale);
// do your drawing
ctx.restore();

Then you add handlers for the appropriate mouse events. For the mouse wheel, this will be the wheel event. Whenever you receive such an event, you'll want to calculate a new scale. This could be done for example using:

// Assuming 'ticks' is some standardized unit of measurement.
// You'll probably want to scale it differently based on event.deltaMode.
var newScale = scale * Math.pow(1.5, ticks);

Then you'll want to figure out the untransformed position.

// Assuming mousePos.x and mousePos.y are the position, relative to the canvas,
// of the mouse event. To untransform, first undo the offset and then undo the
// scale.
var untransformed = {
    x: (mousePos.x - offset.x) / scale,
    y: (mousePos.y - offset.y) / scale
};

Then, perform some magic, determined through experimentation:

offset.x += transformed.x * (scale - newScale);
offset.y += transformed.y * (scale - newScale);

Then apply the scale change:

scale = newScale;

Try it. (written in CoffeeScript there and using clicks rather than scroll, but the math's the same)


Post a Comment for "How Can We Zoom In And Out Of The Graph In Html5 And Javascript?"