简体   繁体   中英

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 ie I want the graph to be zoomed along with its scale on mouse wheel event based on the mouse pointer position so that the graph has more clarity.

I have to achieve it by using HTML5 and JavaScript.

Can anyone guide me on the same?

I asked some people and they said that I have to use vector graphs to achieve it. Is it so?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM