I am creating circles for fun. I am generating them from a function. I want to be able to change their parameters in the console once they are created. Why can’t I do this? My question is specific to this method – why am I not able to change them this way?
a.fill = "black";
written in the console does not change the parameter of the circle object
const container = document.body
let svgContainer = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svgContainer.style.width = "100vw"
svgContainer.style.height = "100vw"
svgContainer.setAttribute("viewBox", "0 0 500 750");
container.appendChild(svgContainer);
function makeCircle(cx, cy, r, fill, stroke, id) {
this.cx = cx;
this.cy = cy;
this.r = r;
this.fill = fill;
this.stroke = stroke;
this.id = id;
let newCircle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
newCircle.setAttribute("cx", cx);
newCircle.setAttribute("cy", cy);
newCircle.setAttribute("r", r);
newCircle.setAttributeNS(null, 'fill', fill);
newCircle.setAttributeNS(null, 'stroke', stroke);
svgContainer.appendChild(newCircle);
}
let a = new makeCircle(50, 300, 20, '#493fea', 'green');
2
Answers
Since you are doing those circles for fun. Here is a modern funny way:
Run the SO snippet; click the viewBox
because you create a new object with a property
cx
for example and seperately from that, a<circle cx="..." />
and the property in your created object and the attribute on the<circle />
have no connection to each other after they were once initially set. You’d have to make such a connection so that when you change the property the attribute is updated.Here an example that does that. It’s a somewhat generic function that takes the name of an element and a list of its specific SVG attributes and then returns a function like your
makeCircle
. But with the mentioned properties on the object.Since it’s generic it doesn’t take attributes like
makeCircle(cx, cy, r, fill, stroke, id)
but instead a single object with the attributes you want to set:makeCircle({ cx, cy, r, fill, stroke, id })
.This is a very basic example, there’s probably a lot to improve upon this.
The code currently doesn’t take into account that some properties should return numbers, every property is a string!