Creating simple shape objects.
This can simplify drawing to canvas:
ellipse.context(canvas).stroke();
It also lets you encapsulates geometry-related helper functions. For example, the parametric function of an ellipse mapping to Cartesian coordinates:
var point = ellipse.cartesian(theta); // point = {x, y}
xxxxxxxxxx
<html>
<head>
<meta charset="utf-8">
<title>Shape Objects</title>
</head>
<body>
<script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="shapes.js"></script>
<script>
var width = 960,
height = 500,
t0 = Date.now();
var canvas = d3.select("body").append("canvas")
.attr("width", width)
.attr("height", height);
var context = canvas.node().getContext("2d");
var ellipse = shapes.ellipse().context(canvas.node());
var circles = d3.range(0, 2*Math.PI, 2*Math.PI/25)
.map(function(t0) {
return {
t0: t0,
shape: shapes.circle().context(canvas.node())
};
});
d3.timer(function() {
var dt = Date.now() - t0,
tick = dt/3000;
context.clearRect(0, 0, width, height);
ellipse
.update(width/2, height/2, 400*Math.cos(tick), 200*Math.sin(tick))
.stroke();
circles.forEach(function(circle) {
var center = ellipse.cartesian(tick + circle.t0),
radius = 5*Math.sin(tick + circle.t0) + 10;
circle.shape
.update(center.x, center.y, radius)
.fill();
});
});
</script>
</body>
</html>
https://d3js.org/d3.v3.min.js