Simple example using d3 to make a simple "wheel" with spokes which spins back and forth.
Designed to show how to use simple shapes and transforms on svgs with d3.
Built with blockbuilder.org
| license: mit |
Simple example using d3 to make a simple "wheel" with spokes which spins back and forth.
Designed to show how to use simple shapes and transforms on svgs with d3.
Built with blockbuilder.org
| <!DOCTYPE html> | |
| <head> | |
| <meta charset="utf-8"> | |
| <script src="https://d3js.org/d3.v4.min.js"></script> | |
| <style> | |
| body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; } | |
| </style> | |
| </head> | |
| <body> | |
| <svg id="svger" width="200px" height="200px"></svg> | |
| <script> | |
| var svg = d3.select('svg') | |
| var margin = 20; | |
| var width = 200, // margin, | |
| height = 200 // margin; | |
| var hub = svg.append('g') | |
| .attr('transform', function(){ | |
| return "translate(" + width/2 + "," + height/2 + ")" | |
| }) | |
| .attr('class', 'hub') | |
| //d3.selectAll('.hub') | |
| hub.append('circle') | |
| .attr('cx', 0) | |
| .attr('cy', 0) | |
| .attr('r', 10) | |
| .attr('fill', 'pink') | |
| hub.append('circle') | |
| .attr('cx', 0) | |
| .attr('cy', 0) | |
| .attr('r', 90) | |
| .attr('stroke', 'red') | |
| .attr('stroke-width', 5) | |
| .attr('fill', 'none') | |
| var linelen = [0, 90]; | |
| var line = d3.line().x(function(d){ | |
| return (0) | |
| }) | |
| .y(function(d){ | |
| return (d) | |
| }) | |
| const numberSpokes = 10; | |
| for( let i = 0; i < numberSpokes; i++) { | |
| var rotation = (360/numberSpokes) * i; | |
| var spoke = hub | |
| .append('path') | |
| .datum(linelen) | |
| .attr('d', line) | |
| .attr('stroke', 'blue') | |
| .attr('transform', 'rotate(' + rotation + ')') | |
| .attr('class', 'spoke') | |
| } | |
| const alreadyTransformed = hub.attr('transform') | |
| rotateIt(false) | |
| function rotateIt(much) { | |
| //console.log(alreadyTransformed) | |
| hub.transition().duration(4000) | |
| .attr('transform', alreadyTransformed + ' rotate(' + (much ? 0 : 180) + ')' ) | |
| .on('end', function(){ | |
| rotateIt(!much) | |
| }) | |
| } | |
| </script> | |
| </body> |