我對此有些麻煩,因爲JavaScript對於類來說似乎很糟糕,而且實現很有趣。我試圖讓這個塊工作,所以我可以創建多個三角形:使用畫布創建和使用類
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();
的問題是,它只是繪製三角形曾經如此我不確定我在這裏做錯了什麼。
他們也可以在'Triangle'中定義'draw()'。 –
啊謝謝你指出。 – samuelk71