Skip to content Skip to sidebar Skip to footer

How To Accurately Zoom D3 Maps Which Have Already Been Translated

I have a map which has been translated to make it fit on the canvas properly. I'm trying to implement a way to zoom it and it does work, but it moves away from center when you zoom

Solution 1:

Here's a comprehensive starting-point: semantic zooming of force directed graph in d3

And this example helped me specifically (just rip out all the minimap stuff to make it simpler): http://codepen.io/billdwhite/pen/lCAdi?editors=001

var zoomHandler = function(newScale) {
        if (!zoomEnabled) { return; }
        if (d3.event) {
            scale = d3.event.scale;
        } else {
            scale = newScale;
        }
        if (dragEnabled) {
            var tbound = -height * scale,
                bbound = height  * scale,
                lbound = -width  * scale,
                rbound = width   * scale;
            // limit translation to thresholds
            translation = d3.event ? d3.event.translate : [0, 0];
            translation = [
                Math.max(Math.min(translation[0], rbound), lbound),
                Math.max(Math.min(translation[1], bbound), tbound)
            ];
        }

        d3.select(".panCanvas, .panCanvas .bg")
            .attr("transform", "translate(" + translation + ")" + " scale(" + scale + ")");

        minimap.scale(scale).render();
    }; // startoff zoomed in a bit to show pan/zoom rectangle

Though I had to tweak that function a fair bit to get it working for my case, but the idea is there. Here's part of mine. (E.range(min,max,value) just limits value to be within the min/max. The changes are mostly because I'm treating 0,0 as the center of the screen in this case.

// limit translation to thresholdsvar offw = width/2*scale;
            var offh = height/2*scale;
            var sw = width*scale/2 - zoomPadding;
            var sh = height*scale/2- zoomPadding;

            translate = d3.event ? d3.event.translate : [0, 0];
            translate = [
                E.range(-sw,(width+sw), translate[0]+offw),
                E.range(-sh,(height+sh), translate[1]+offh)
            ];
        }


        var ts = [translate[0], translate[1]];
        var msvg  = [scale, 0, 0, scale, ts[0], ts[1]];

Post a Comment for "How To Accurately Zoom D3 Maps Which Have Already Been Translated"