D3.js Template
CSS
.axis {
shape-rendering: crispEdges;
}
.axis path, .axis line {
fill: none;
stroke-width: .5px;
}
.x.axis path {
stroke: #000;
}
.x.axis line {
stroke: #fff;
stroke-opacity: .5;
}
.y.axis line {
stroke: #ddd;
}
path.line {
fill: none;
stroke: #000;
stroke-width: .5px;
}
rect.pane {
cursor: move;
z-index: 100000;
fill: none;
pointer-events: all;
}
JavaScript
var svg = d3.select('svg');
var dataSet = [
{
start: new Date('1 Feb 2014'),
end: new Date('2 Feb 2014')
},
{
start: new Date('1 Feb 2014'),
end: new Date('2 Feb 2014')
}, {
start: new Date('3 Feb 2014'),
end: new Date('4 Feb 2014')
}, {
start: new Date('4 Feb 2014'),
end: new Date('5 Feb 2014')
}];
var width = 400, height = 100;
var x = d3.time.scale().range([0, width]).domain([new Date('1 Feb 2014'), new Date('5 Feb 2014')]);
var y = d3.scale.linear().domain([0, 100]).range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.ticks(6)
.tickPadding(6);
var zoom = d3.behavior.zoom().on("zoom", draw);
var itemRects = svg.append('g').attr('clip-path', 'url(#clip)');
svg.append("clipPath")
.attr("id", "clip")
.append("rect")
.attr("x", x(0))
.attr("y", y(1))
.attr("width", x(1) - x(0));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (height - 25) + ")");
svg.append("path")
.attr("class", "line")
.attr("clip-path", "url(#clip)");
svg.append("rect")
.attr("class", "pane")
.attr("width", width)
.attr("height", height)
.call(zoom);
svg.selectAll('text')
.data(dataSet)
.enter()
.append('text')
.attr('class', 'thetext')
.attr('x', function (d) {
return x(d.start);
})
.attr('y', function (d) {
return 10;
})
.text("should not distort on zoom");
svg.selectAll('rect')
.data(dataSet)
.enter()
.append('rect')
.attr('class', 'timebar')
.style('opacity', 0.3)
.style('fill', "green")
.attr('x', function (d) {
return x(d.start);
})
.attr('width', function (d) {
return x(d.end) - x(d.start);
})
.attr('height', function (d) {
return 2.5;
})
zoom.x(x);
draw();
function draw() {
if (d3.event) {
svg.selectAll("rect.timebar").attr("transform", "translate(" + d3.event.translate[0] + ",0)scale(" + d3.event.scale + ", 1)");
...