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


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.bottom;

self.svg ="body").append("svg:svg")
            .attr("width", self.width)
            .attr("height", self.height)
            .attr("transform", "translate(" + self.margin.left + "," + + ")");

    .attr("height", 40)
    .attr("y", 100)
    .attr("x", 100)
    .style("fill", "steelblue");

    .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