D3 - Moving images with tooltip
Nayana Das
by Nayana Das
HTML
<script src="https://d3js.org/d3.v3.min.js"></script>
CSS
.overlay {
fill: none;
pointer-events: all;
}
div.tooltip {
position: absolute;
text-align: center;
width: 60px;
height: 28px;
padding: 2px;
font: 12px sans-serif;
background: lightsteelblue;
border: 0px;
border-radius: 8px;
pointer-events: none;
}
JavaScript
var imgHeight = 1025,
imgWidth = 1538, // Image dimensions (don't change these)
width = 500,
height = 500, // Dimensions of cropped region
translate0 = [-290, -180],
scale0 = 1; // Initial offset & scale
svg = d3.select("body").append("svg")
.attr("width", width + "px")
.attr("height", height + "px");
svg.append("rect")
.attr("class", "overlay")
.attr("width", width + "px")
.attr("height", height + "px");
svg = svg.append("g")
.attr("transform", "translate(" + translate0 + ")scale(" + scale0 + ")")
.call(d3.behavior.zoom().scaleExtent([1, 8]).on("zoom", zoom))
.append("g");
var div = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
svg.append("image")
.attr("width", imgWidth + "px")
.attr("height", imgHeight + "px")
.attr("xlink:href", "http://www.myfreetextures.com/wp-content/uploads/2015/01/deep-green-grass-texture.jpg");
function zoom() {
svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
console.log("translate: " + d3.event.translate + ", scale: " + d3.event.scale);
}
var max = 400,
min = 200;
var icons = ["user", "user", "table", "gate"];
svg.selectAll("image.icon")
.data(icons)
.enter()
.append("image")
.classed("icon", true)
.attr("id", function(d, i) {
if(d=="user"){
return "user" + i;
}else if(d=="table"){
return "table" + i;
}else if(d=="gate"){
return "gate" + i;
}
})
.attr('x', function() {
return Math.floor(Math.random() * (max - min + 1) + min);
})
.attr('y', function() {
return Math.floor(Math.random() * (max - min + 1) + min);
})
.attr('width', 30)
.attr('height', 24)
.attr("xlink:href", "http://www.worryfreelabs.com/wp-content/uploads/2016/06/WFl_logo-2015-icon-only-white-background.png")
.on("mouseover", function(d, i) {
div.transition()
.duration(200)
.style("opacity", .9);
console.log(d);
if(d=="user"){
div.html("user...