Domanda

I'm playing around with maps in D3. Right now I only have the USA showing up, and I've implemented some zooming and panning functionality. The question I have is: is it possible to allow a user to zoom/pan from any point? That is, you can only zoom or pan if the mouse is directly over a piece of the map or any other svg element (i.e. not whitespace). Can I extend this to the entire window? I've done this before by adding a huge background rectangle that could register the events, but that feels a little hacky and I feel like there's a better way. Thanks for any advice!

EDIT: It looks like I accidentally figured it out playing around with some example code :p

È stato utile?

Soluzione

Here is an example that i made to understand the most basic zoom behaviour in D3.js

A canvas (svg) is appended to the body of the HTML. Then a blue rectangle is appended and then a red rectangle is appended. The zoom behaviour is added with the line

.call(d3.behavior.zoom().on("zoom",redraw))

here the redraw function is called when D3 detects that a "zoom" was triggered on the canvas.

The code example is invoked in a "class" object in javaScript:

function ExampleZoom(){
/*** Class defining a zoomable svg. SVG AKA canvas in HTML5 ***/
var self = this;

self.margin = {top: 20, right: 20, bottom: 30, left: 40};
self.width = 960 - self.margin.left - self.margin.right;
self.height = 500 - self.margin.top - self.margin.bottom;

self.svg = d3.select("body").append("svg:svg")
            .attr("width", self.width)
            .attr("height", self.height)
            .call(d3.behavior.zoom().on("zoom",redraw))
            .append("g")
            .attr("transform", "translate(" + self.margin.left + "," + self.margin.top + ")");

self.svg.append("svg:rect")
    .attr("width",40)
    .attr("height", 40)
    .attr("y", 100)
    .attr("x", 100)
    .style("fill", "steelblue");

self.svg.append("svg:rect")
    .attr("width",10)
    .attr("height", 10)
    .attr("y", 200)
    .attr("x", 200)
    .style("fill", "red");

//Redraw for zoom
function redraw() {
    console.log("here", d3.event.translate, d3.event.scale);
    self.svg.attr("transform","translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")");
}
}//End of class

var ex = new ExampleZoom();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top