JSFiddle - React, Tailwind, and code Playground
by Gabriel Z
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<div id="test">
<svg></svg>
</div>
CSS
.axis path,
.axis line {
fill: none;
stroke: #eee;
shape-rendering: crispEdges;
}
rect {
fill: red;
}
JavaScript
var defects = [
{ x: 50, y: 600, width: 50, height: 20 },
{ x: 500, y: 800, width: 35, height: 65 },
{ x: 950, y: 600, width: 50, height: 100 },
{ x: 400, y: 8600, width: 50, height: 20 },
{ x: 300, y: 7600, width: 50, height: 20 },
{ x: 350, y: 9600, width: 50, height: 20 }];
var length = 10000;
var width = 1000;
var pixelWidth = 450;
var pixelHeight = 600;
var xScale = d3.scale.linear()
.domain([0, width])
.range([0, pixelWidth]);
var yScale = d3.scale.linear()
.domain([0, length])
.range([0, pixelHeight]);
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("top")
.tickFormat(d3.format('.f'))
.tickSize(pixelHeight);
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left")
.tickFormat(d3.format('.f'))
.tickSize(-pixelWidth);
var zoom = d3.behavior.zoom()
.x(xScale)
.y(yScale)
.scaleExtent([1, 20])
.on("zoom", zoomed);
var svg = d3.select('#test svg')
.attr("width", pixelWidth)
.attr("height", pixelHeight)
.call(zoom);
var rects = svg.append('g').selectAll("rect")
.data(defects)
.enter()
.append('rect')
.attr("width", function (d) {
return xScale(d.width);
})
.attr("height", function (d) {
return yScale(d.height);
})
.attr("transform", function(d) {
return "translate(" + xScale(d.x) + "," + yScale(d.y) + ")"; }
);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (pixelHeight) + ")" )
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
function zoomed() {
rects.attr('transform', function (d) {
return "translate(" + xScale(d.x) + "," + yScale(d.y) + ")scale(" + d3.event.scale + ")"; });
svg.select(".x.axis").call(xAxis);
svg.select(".y.axis").call(yAxis);
}