These are my first baby steps in , a new(ish) JavaScript library that was developed by (i.e. a data science guru) for creating data visualizations. In fact, D3 stands for “Data Driven Documents”, and as the name suggests, it’s really a general purpose framework for doing pretty much anything one could want to do with data these days. I’m not only new to D3, but also to JS, which I am forcing myself to learn so I can take advantage of D3 (having seen the coolness of it, I couldn’t let something as small as not knowing JS hold me back).
There doesn’t appear to be a D3 book yet, so one has to go about finding tutorials in various places. There are going around, though. I found from Scott Murray () particularly valuable.
As I learn D3, I intend to post from time to time during each stage of my development. Hopefully, progress will be evident in both my understanding of D3 and JavaScript. Here, I just wanted to get going by doing a very simple animation of a “gun” “shooting” a “bullet”. To make it just a little bit more interesting, I added a random component which changes how far the bullet goes each time. Click on the “Shoot!” button to refresh the page which will re-load (i.e. restart) the animation.
To simulate recoil in the gun, I used the .ease("bounce")
function, and to simulate the bullet slowing down, I used .ease("exp-out")
. I tried to make it somewhat realistic by multiplying the recoil distance and bullet travel by the same random factor (factor = Math.random()
). Everything else should be fairly self-explanatory. One thing I like about D3 is that it almost seems to document itself (how meta!).
Simulation of gun firing bullet
HTML/JS Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.v2.js"></script>
</head>
<body>
<div id="chart"></div>
<div id="button">
<input type="button" id="Button1" value="Shoot!" onclick="history.go(0)"/>
<script type="text/javascript">
var w = 500,
h = 300,
factor = Math.random(),
draw = d3.select("#chart")
.append("svg")
.attr("width",w)
.attr("height",h);
draw.append("rect")
.attr("x",0)
.attr("y",0)
.attr("width",500)
.attr("height",300)
.attr("fill","lightgray")
.attr("stroke","black")
.attr("stroke-width",5);
draw.append("circle")
.attr("id","cir1")
.attr("cx",170)
.attr("cy",160)
.attr("r",12.5)
.attr("fill","steelblue")
.transition()
.ease("exp-out")
.duration(1500)
.attr("transform",function(){
return "translate("+factor*250+",0)";
});
draw.append("rect")
.attr("id","rect1")
.attr("x",50)
.attr("y",150)
.attr("width",100)
.attr("height",25)
.attr("fill","black")
.transition()
.ease("bounce")
.duration(1500)
.attr("transform",function(){
return "translate("+factor*(-25)+")";
});
</script>
</body>
</html>
|
Categories :animation • simulation • tutorial • Uncategorized