我试图沿着x轴移动弧线,但是它给出了一个错误,即x未在更新函数中定义。变量没有正确放置或缺少某些参考吗?
代码
<canvas id="myCanvas"></canvas>
<script>
var myCanvas = document.getElementById("myCanvas");
var c = myCanvas.getContext("2d");
var redArc = new Circle(50, 60, 10, "red");
var greenArc = new Circle(80, 60, 15, "green");
var blueArc = new Circle(120, 60, 20, "blue");
function Circle(x, y, radius, color) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.draw = function() {
c.beginPath();
c.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
c.fillStyle = this.color;
c.fill();
}
this.update = function() {
redArc.x += 1;
greenArc.x += 1;
blueArc.x += 1;
this.draw();
}
this.update();
}
function animate() {
requestAnimationFrame(animate);
c.clearRect(0, 0, myCanvas.clientWidth, myCanvas.clientHeight);
redArc.update();
greenArc.update();
blueArc.update();
}
animate();
我该如何修复它?有什么建议 谢谢!
答案 0 :(得分:2)
将 update
方法替换为以下内容:
this.update = function() {
this.x += 1;
this.draw();
}
您应该使用this.x
,而不是变量名称。
var myCanvas = document.getElementById("myCanvas");
var c = myCanvas.getContext("2d");
var redArc = new Circle(50, 60, 10, "red");
var greenArc = new Circle(80, 60, 15, "green");
var blueArc = new Circle(120, 60, 20, "blue");
function Circle(x, y, radius, color) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.draw = function() {
c.beginPath();
c.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
c.fillStyle = this.color;
c.fill();
}
this.update = function() {
this.x += 1;
this.draw();
}
this.update();
}
function animate() {
c.clearRect(0, 0, myCanvas.clientWidth, myCanvas.clientHeight);
redArc.update();
greenArc.update();
blueArc.update();
requestAnimationFrame(animate);
}
animate();
<canvas id="myCanvas"></canvas>