概要 实例 介绍 源码

方圆螺旋错觉

源文件:index.html

  1. <!DOCTYPE html>
  2. <meta charset="utf-8">
  3. <style>
  4. body {
  5. background: #888;
  6. }
  7. rect {
  8. fill: none;
  9. stroke: #000;
  10. stroke-width: 2.5px;
  11. }
  12. .square:nth-child(2n + 1) rect {
  13. stroke: #fff;
  14. }
  15. </style>
  16. <body>
  17. <script src="//d3js.org/d3.v3.min.js"></script>
  18. <script>
  19. var w = 960,
  20. h = 500,
  21. start = Date.now();
  22. var rings = [
  23. {radius: 65 * 1, width: 16, speed: -3e-2},
  24. {radius: 65 * 2, width: 16, speed: -2e-2},
  25. {radius: 65 * 3, width: 16, speed: -1e-2},
  26. {radius: 65 * 4, width: 16, speed: 1e-2},
  27. {radius: 65 * 5, width: 16, speed: 2e-2},
  28. {radius: 65 * 6, width: 16, speed: 3e-2}
  29. ];
  30. var svg = d3.select("body").append("svg")
  31. .attr("width", w)
  32. .attr("height", h)
  33. .append("g")
  34. .attr("transform", "translate(" + w / 2 + "," + h / 2 + ")scale(.6)");
  35. var ring = svg.selectAll("g")
  36. .data(rings)
  37. .enter().append("g")
  38. .attr("class", "ring")
  39. .each(ringEnter);
  40. d3.timer(function() {
  41. var elapsed = Date.now() - start,
  42. rotate = function(d) { return "rotate(" + d.speed * elapsed + ")"; };
  43. ring
  44. .attr("transform", rotate)
  45. .selectAll("rect")
  46. .attr("transform", rotate);
  47. });
  48. function ringEnter(d, i) {
  49. var n = Math.floor(2 * Math.PI * d.radius / d.width * Math.SQRT1_2),
  50. k = 360 / n;
  51. d3.select(this).selectAll("g")
  52. .data(d3.range(n).map(function() { return d; }))
  53. .enter().append("g")
  54. .attr("class", "square")
  55. .attr("transform", function(_, i) { return "rotate(" + i * k + ")translate(" + d.radius + ")"; })
  56. .append("rect")
  57. .attr("x", -d.width / 2)
  58. .attr("y", -d.width / 2)
  59. .attr("width", d.width)
  60. .attr("height", d.width);
  61. }
  62. </script>