The aim of this puzzle: Draw a circle.
Walkthrough of the solution: The code that you start with for drawing a rectangle is very similar to what you need to draw a circle. Let’s take a look at each part of the command and build a similar command for our circle. var rect
is creating a variable called rect
– that’s nothing new. Next, =
says that we’re going to give the variable something to store inside of it. Now for the new part: svg.append('rect');
The svg
stands for Scalable Vector Graphics which are basically shapes that the computer sees as “connect the dots” – connected with straight lines or sometimes different types of curves. This might be different from the way you usually think of computerized pictures because zooming into an SVG doesn’t get blurry or pixelated. .append()
is a command to add something to the screen. In the example line, svg.append('rect')
adds a rectangle to the screen, similar to how you would use drawBox('red')
to draw a red box. But instead of a color, you tell it a shape. That lets you use 'circle'
inside of .append()
to create a circle! So, to create a circle, you make a new variable (maybe you could just call it circle
), and then assign to it: svg.append('circle')
Sample code solution:
(Tap below to reveal)
var rect = svg.append('rect');
var circle = svg.append('circle');
JavaScript Concepts: Identifiers, Member Expression, Variable Declaration
D3 Concepts: .append()
Additional Code (hidden code that runs before the puzzle’s code):
class D4 {
constructor(d3) {
this.d3 = d3;
}
attr(key, value) {
this.d3.attr(key, value);
return this;
}
append(name) {
const result = this.d3.append(name);
result._groups[0].forEach(el => {
// list shapes and attributes to change here:
if (el.tagName === 'rect') {
el.setAttribute('x', 25);
el.setAttribute('y', 25);
el.setAttribute('width', 100);
el.setAttribute('height', 100);
el.setAttribute('fill','pink');
}
if (el.tagName === 'circle') {
el.setAttribute('r', 50);
el.setAttribute('cx', 75);
el.setAttribute('cy', 75);
el.setAttribute('fill', 'blue');
}
});
return this;
}
}
var svg = new D4(d3.select('body').append('svg').attr('width',500).attr('height',500));