score:0

Accepted answer

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();

Related Query

More Query from same tag