我们如何在html5和javascript中放大和缩小图形? [英] 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 position so that the graph has more clarity.
我必须使用HTML5和JavaScript来实现它。
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?
推荐答案
为了做到这一点,你必须有一个偏移量和缩放比例。然后,无论何时绘制,您都必须适当地转换绘图。 Canvas使这很简单:
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();
然后为适当的鼠标事件添加处理程序。对于鼠标滚轮,这将是 wheel
活动。每当您收到此类事件时,您都需要计算新的比例。这可以通过以下方式完成:
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);
然后应用比例更改:
scale = newScale;
试一试。 (用CoffeeScript编写并使用点击而非滚动,但数学相同)
Try it. (written in CoffeeScript there and using clicks rather than scroll, but the math's the same)
这篇关于我们如何在html5和javascript中放大和缩小图形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!