D3.ver 4 - ツリーマップを使ってイメージギャラリーを作ってみた。
Built with blockbuilder.org
license: mit |
D3.ver 4 - ツリーマップを使ってイメージギャラリーを作ってみた。
Built with blockbuilder.org
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8" /> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"/> | |
<title>D3 v4 - Image Gallery </title> | |
<style> | |
html, body{ | |
width: 100%; | |
height: 100%; | |
padding: 0px; | |
margin: 0px; | |
} | |
#graph { | |
width: 100%; | |
height: 100%; | |
} | |
.node { | |
position: absolute; | |
background-size:cover; | |
} | |
</style> | |
</head> | |
<body> | |
<div id="graph"></div> | |
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/4.1.1/d3.min.js"></script> | |
<script> | |
!(function(){ | |
"use strict" | |
var data = [ | |
{id:"root",value:null}, | |
{id:"root.1",value:null,img:"img1.jpg"}, | |
{id:"root.2",value:null,img:"img2.jpg"}, | |
{id:"root.3",value:null,img:"img3.jpg"}, | |
{id:"root.4",value:null,img:"img4.jpg"}, | |
{id:"root.5",value:null,img:"img5.jpg"}, | |
]; | |
var width = document.querySelector("#graph").clientWidth; | |
var height = document.querySelector("#graph").clientHeight; | |
var div = d3.select("#graph").append("div").attr("width", width).attr("height", height); | |
setInterval(draw, 2000); | |
draw(); | |
function draw() { | |
randomize(); | |
var stratify = d3.stratify() | |
.parentId(function(d) {return d.id.substring(0, d.id.lastIndexOf(".")); }); | |
var root = stratify(data).sum(function(d) { return d.value ;}); | |
var treemap = d3.treemap() | |
.tile(d3.treemapBinary) | |
.size([width, height]) | |
.padding(1) | |
.round(true); | |
treemap(root); | |
drawTreemap(root); | |
} | |
function randomize() { | |
data.filter(function(d){ return d.id !== "root" ; }) | |
.forEach(function(d){ | |
d.value = ~~(d3.randomUniform(1, 10)()); | |
}); | |
} | |
function drawTreemap(root) { | |
var node = div.selectAll(".node").data(root.children); | |
var newNode = node.enter() | |
.append("div").attr("class", "node") | |
.style("background-image", function(d){ return "url(" + d.data.img + ")";}); | |
node.merge(newNode) | |
.transition() | |
.duration(1000) | |
.style("left", function(d) { return d.x0 + "px" ;}) | |
.style("top", function(d) { return d.y0 + "px" ;}) | |
.style("width", function(d) { return (d.x1 - d.x0) + "px" ;}) | |
.style("height", function(d) { return (d.y1 - d.y0) + "px" ;}); | |
} | |
}()); | |
</script> | |
</body> | |
</html> |