トランジション終了後に背景色を変更します。
Last active
March 7, 2018 09:21
-
-
Save shimizu/8998fb9899e65b3196d5690182b674cb to your computer and use it in GitHub Desktop.
D3 Transition - use Promise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<head> | |
<meta charset="utf-8"> | |
<style> | |
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } | |
svg { width:100%; height: 100% } | |
</style> | |
</head> | |
<body> | |
<button>transition</button> | |
<svg></svg> | |
<script src="//unpkg.com/babel-standalone@6.26.0/babel.min.js"></script> | |
<script src="//unpkg.com/d3@4.12.2/build/d3.min.js"></script> | |
<script type="text/babel"> | |
const svg = d3.select('svg') | |
const circle = svg.append("circle") | |
.attr("cx", 100) | |
.attr("cy", 50) | |
.attr("r", 20) | |
const rect = svg.append("rect") | |
.attr("x", 100) | |
.attr("y", 100) | |
.attr("width", 30) | |
.attr("height", 30) | |
const line = svg.append("line") | |
.attr("x1", 100) | |
.attr("y1", 150) | |
.attr("x2", 100) | |
.attr("y2", 150) | |
.attr("stroke", "black") | |
//D3のトランジションをpromiseで包む | |
const p1 = () => { | |
return new Promise((resolve, reject) => { | |
circle.transition().duration(Math.floor(Math.random()*5000)) | |
.attr("cx", 800) | |
.on("end", resolve) | |
}) | |
} | |
const p2 = () => { | |
return new Promise((resolve, reject) => { | |
rect.transition().duration(Math.floor(Math.random()*5000)) | |
.attr("x", 800) | |
.on("end", resolve) | |
}) | |
} | |
const p3 = () => { | |
return new Promise((resolve, reject) => { | |
line.transition().duration(Math.floor(Math.random()*5000)) | |
.attr("x2", 800) | |
.on("end", resolve) | |
}) | |
} | |
d3.select("button").on("click", function(){ | |
//ポジションをリセット | |
d3.select("body").style("background-color", "white") | |
circle.attr("cx", 100) | |
rect.attr("x", 100) | |
line.attr("x2", 100) | |
//トランジション開始 | |
Promise.all([p1(), p2(), p3()]).then(endFn) | |
}) | |
//トランジションが終了したら背景色を変える | |
function endFn(){ | |
d3.select("body").style("background-color", "pink") | |
} | |
</script> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment