gpt4 book ai didi

javascript - 无法使用 JS 在 Canvas 中移动 Arc

转载 作者:行者123 更新时间:2023-12-01 03:14:34 24 4
gpt4 key购买 nike

我试图沿 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();

我该如何修复它?有什么建议谢谢!!

最佳答案

将您的 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>

关于javascript - 无法使用 JS 在 Canvas 中移动 Arc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45633375/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com