i having trouble because javascript seems terrible classes , implementation interesting. trying block working can create multiple triangles:
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(); (var = 0; <= sides; i++) { context[i ? 'lineto' : 'moveto']( centerx + size * math.cos(phase + / sides * tau), centery + size * math.sin(phase + / sides * tau) ); } context.stroke(); } animate();
and here tried making class:
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(); (var = 0; <= sides; i++) { this.ctx[i ? 'lineto' : 'moveto']( centerx + size * math.cos(phase + / sides * tau), centery + size * math.sin(phase + / sides * tau) ); } this.ctx.stroke(); } var triangle1 = new triangle(context,canvas); triangle1.draw();
the problem draws triangle once not sure doing wrong here.
the problem here you're calling requestanimationframe
, passing callback same function, this
keyword refer window
object, , not class anymore.
so, must explicit want set context of callback function same context are, , can achieve calling .bind(this)
. take @ example below:
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(); (var = 0; <= sides; i++) { this.ctx[i ? 'lineto' : 'moveto']( centerx + size * math.cos(phase + / sides * tau), centery + size * math.sin(phase + / sides * tau) ); } this.ctx.stroke(); } var triangle1 = new triangle(context, canvas); triangle1.draw();
<canvas></canvas>
Comments
Post a Comment