Kaleidoscope Puzzle Explainer


Aim of the puzzle :
Use the d3.selectAll() method to set an attribute on all instances of a type of shape.

Walk through of solution :
The d3.selectAll() method selects all instances of a type of shape. For example, d3.selectAll('circle') selects every circle and d3.selectAll('rect') selects every rectangle. Once all the instances of a shape are selected, you can set all of their attributes using one .attr() .

In the code that you start off with, there is an incomplete squares variable declaration and a .transition() animation. Since the squares variable is incomplete, the .transition() doesn’t have anything to animate on and won’t run. In this puzzle, you’ll use d3.selectAll() to update the squares variable so the animation runs on all the rectangles.

To complete the puzzle, attach .selectAll() to end of d3 and use 'rect' as an argument. Now, the animation works and each rectangle will be a different color.

Sample code solution:
(Tap below to reveal)

let squares = d3.selectAll('rect');

Javascript Concepts: Variable
D3 Concepts: Attribute, .transition(), d3.selectAll()
Additional Code:

const color = [...Array(36)].map((_, i) => `hsl(${10 * i},100%,50%)`);

let s = 20;
for (let i = 1; i < window.innerWidth; i += s) {
  for (let j = 1; j < window.innerHeight; j += s) {
      .attr("fill", `hsl(${i*j},100%,50%)`)
      .attr("width", s)
      .attr("height", s)
      .attr("transform", `translate(${i},${j}) rotate(${Math.random() * 90}, ${s / 2}, ${s / 2})`);
listed #2