简体   繁体   中英

Pinch zoom on touch devices

I have a graph rendered within the HTML5 canvas. The working is good till this point. Now I need to implement pinch zoom on the graph for touch devices. The logic is as the two finger stretches apart the graph zooms in and as the finger moves together the graph zooms out. In this case we need to constantly update the axis value. The problem here is how do we get the individual X and Y axis value of both the fingers and then calculate the amount of zoom to be done. As for example, for zooming using mouse we can get the start X and Y value on mouse down and on mouse up we get the end X and Y axis value. Using this start and end value of X and Y axis the graph can be zoomed accordingly. The canvas should not zoom in/out. The zoom in can be infinite but the zoom out will be till the default plotting of the graph. Any idea or help would be really appreciable. I am not getting the proper calculation.

I have implemented it in the following way. Any suggestions are welcome.

First I have taken the screen co-ordinates of the two fingers touch on start and converted it to its corresponding view co-ordinates by calculating its distance from the topmost and leftmost position. After that I have calculated the scale and new co-ordinates for X-axis in the following way.

Let d1 and d2 be the dataspace coordinates of the initial/starting touches. newx1 and newx2 are the x positions of the new touches. screenW is the current screen width (ie width of plot in screen space).

Then scale = (d2 - d1) / (newx2 - newx1)

If we use newd1, newd2 to denote the new datarange min and max values that we're trying to compute:

newd1 = d1 - newx1 * scale

newd2 = newd1 + screenW * scale

Similarly, we can do the calculation for new datarange min and max values of Y-axis.

Variant A :

Take a JavaScript library like Hammer.js which abstracts away all then event handling and gives you an event in case of a pinch. This should look like this:

var element = document.getElementById('test_el');
var hammertime = Hammer(element).on("pinchout", function(event) {
    console.log("Zoom out!!");
    // event.scale should contain the scaling factor for the zoom
});

Variant B :

Read about the touch events and how to identify if it is a multitouch. Figure out when it is a pinch and if how far the fingers have moved. There is nice write up here .

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