无法使用JS在画布中移动Arc [英] Unable to move Arc in a canvas using JS
本文介绍了无法使用JS在画布中移动Arc的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试沿x轴移动圆弧,但是它给出了一个错误,即未在更新函数中定义x.变量放置不正确或缺少参考吗?
I am trying to move the arcs along the x-axis, but it's giving an error that x is not defined in the update function. Are the variables not properly placed or some reference is missing??
代码
<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();
我该如何解决?有什么建议 谢谢!
How do I go about fixing it? Any suggestions Thanks!!
推荐答案
将您的 update
方法替换为以下内容:
Replace your update
method with the following :
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>
这篇关于无法使用JS在画布中移动Arc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文