我真的不知道为什么当我运行此代码时出现此错误: 未捕获的TypeError:无法设置属性' cx'未定义的。 我真的会学习如何使用class在svg圈子上设置属性。
<svg id="svg" xmlns="http://www.w3.org/2000/svg">
</svg>
<script>
class Pelota {
constructor( coorx, coory, radius, colour){
this.parent = document.getElementById("svg");
this.circulo =document.createElementNS("http://www.w3.org/2000/svg", "circle");
this.parent.appendChild(this.circulo);
this.circulo.attribute.cx = coorx; //here's the error
this.circulo.attribute.cy = coory;
this.circulo.attribute.r = radius;
this.circulo.attribute.fill = colour;
this.avancex = 1;
this.avancey = 1;
}
move() {
this.circulo.attribute.cx =+ this.avancex;
this.circulo.attribute.cy =+ this.avancey;
}
}
var pelotica = new Pelota( 60, 60, 60, "red");
pelotica.move();
</script>
答案 0 :(得分:0)
通过setAttribute方法或SVG DOM设置属性。 SVG DOM不使用属性属性。
我已经展示了SVG DOM下面的两种方法都在移动函数中使用,因为它更简单,因为SVG DOM会给你一个数字而不是一个字符串。我还修改了移动命令中从= +到+ =
的语法
<svg id="svg" xmlns="http://www.w3.org/2000/svg">
</svg>
<script>
class Pelota {
constructor( coorx, coory, radius, colour){
this.parent = document.getElementById("svg");
this.circulo =document.createElementNS("http://www.w3.org/2000/svg", "circle");
this.parent.appendChild(this.circulo);
this.circulo.setAttribute("cx", coorx); //here's the error
this.circulo.setAttribute("cy", coory);
this.circulo.setAttribute("r", radius);
this.circulo.setAttribute("fill", colour);
this.avancex = 1;
this.avancey = 1;
}
move() {
this.circulo.cx.baseVal.value += this.avancex;
this.circulo.cy.baseVal.value += this.avancey;
}
}
var pelotica = new Pelota( 60, 60, 60, "red");
pelotica.move();
</script>