Aim of the puzzle:
This puzzle combines the use of JavaScript concepts (objects, variables, and functions) and D3 concepts ('cx'
, 'cy'
, and 'r'
attributes) to create and modify shapes.
Specifically, you’ll use a function to create a modified version of an object whose properties then get used as values for the attributes of a shape.
Walk through of solution:
In the code that you start off with, there are two variables, circle
and newCircle
, a function, change
, and 2 SVG circles, pea1
and pea2
. circle
is an object containing three properties: cx
, cy
, and r
. The change
function takes an object, modifies the values of its properties, and returns it as a new object. pea1
and pea2
are SVG circles that use the values of the cx
, cy
and r
properties of newCircle
for their 'cx'
, 'cy'
, and 'r'
attributes. As it is, newCircle
is currently the same as circle
. In this puzzle, you’ll change newCircle
so it calls the change
function on circle
to create an object with the same properties, but different values, as circle
.
To complete the puzzle, change the value of the newCircle
variable from circle
to change(circle)
. Now, the 'cx'
and 'cy'
attributes of pea1
and pea2
will be different from the values of the cx
and cy
properties of circle
.
Sample code solution:
(Tap below to reveal)
let circle = {
cx: 50,
cy: 50,
r: 50
};
function change (object){
let newObject = {
cx: object.cx + pickRandom(100),
cy: object.cy + pickRandom(150),
r: object.r
};
return newObject;
}
let newCircle = change(circle);
pea1.attr('cx', newCircle.cx ).attr('cy', newCircle.cy);
pea2.attr('cx', newCircle.cx + (newCircle.r * 2) ).attr('cy', newCircle.cy);
Javascript Concepts: Variable, Function, Object
D3 Concepts: Attribute
Additional Code (hidden code that runs before the puzzle’s code):
var svg = canvas.append('g');
let pea1 = svg.append('circle').attr('fill', 'green').attr('r', 50)
let pea2 = svg.append('circle').attr('fill', 'lime').attr('r', 50)