gpt4 book ai didi

javascript - 使用 Canvas 创建和使用类

转载 作者:行者123 更新时间:2023-11-30 00:21:55 25 4
gpt4 key购买 nike

我在这方面遇到了一些麻烦,因为 Javascript 对于类来说似乎很糟糕,而且实现很有趣。我试图让这个 block 工作,所以我可以创建多个三 Angular 形:

var canvas = document.querySelector('canvas');
var context = canvas.getContext('2d');
var phase = 0;
var tau = 2 * Math.PI;

function animate() {
requestAnimationFrame(animate);
var sides = 3;
var size = 100;
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
phase += 0.005 * tau;

context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
for (var i = 0; i <= sides; i++) {
context[i ? 'lineTo' : 'moveTo'](
centerX + size * Math.cos(phase + i / sides * tau),
centerY + size * Math.sin(phase + i / sides * tau)
);
}
context.stroke();
}

animate();

在这里我试着把它变成一个类:

var canvas = document.querySelector('canvas');
var context = canvas.getContext('2d');
var phase = 0;
var tau = 2 * Math.PI;

function Triangle(cntx, canvs) {
this.ctx = cntx;
this.canv = canvs;
this.draw = drawTriangle;
}
function drawTriangle() {
requestAnimationFrame(drawTriangle);
var sides = 3;
var size = 100;
var centerX = this.canv.width / 2;
var centerY = this.canv.height / 2;
phase += 0.005 * tau;

this.ctx.clearRect(0, 0, this.canv.width, this.canv.height);
this.ctx.beginPath();
for (var i = 0; i <= sides; i++) {
this.ctx[i ? 'lineTo' : 'moveTo'](
centerX + size * Math.cos(phase + i / sides * tau),
centerY + size * Math.sin(phase + i / sides * tau)
);
}
this.ctx.stroke();
}

var triangle1 = new Triangle(context,canvas);
triangle1.draw();

问题是它只绘制了一次三 Angular 形,所以我不确定我在这里做错了什么。

最佳答案

这里的问题是您正在调用 requestAnimationFrame 并将回调传递给同一函数,但是 this 关键字将引用 window 对象,不再是你的类。

因此,您必须明确表示要将回调函数的上下文设置为与您当前相同的上下文,并且可以通过调用 .bind(this) 来实现。看看下面的例子:

var canvas = document.querySelector('canvas');
var context = canvas.getContext('2d');
var phase = 0;
var tau = 2 * Math.PI;

function Triangle(cntx, canvs) {
this.ctx = cntx;
this.canv = canvs;
this.draw = drawTriangle;
}

function drawTriangle() {
requestAnimationFrame(drawTriangle.bind(this));
var sides = 3;
var size = 100;
var centerX = this.canv.width / 2;
var centerY = this.canv.height / 2;
phase += 0.005 * tau;

this.ctx.clearRect(0, 0, this.canv.width, this.canv.height);
this.ctx.beginPath();
for (var i = 0; i <= sides; i++) {
this.ctx[i ? 'lineTo' : 'moveTo'](
centerX + size * Math.cos(phase + i / sides * tau),
centerY + size * Math.sin(phase + i / sides * tau)
);
}
this.ctx.stroke();
}

var triangle1 = new Triangle(context, canvas);
triangle1.draw();
<canvas></canvas>

关于javascript - 使用 Canvas 创建和使用类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32792226/

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