javascript - How to orient custom canvas shape on position -


in attempt learn javascript, i'm making asteroids game. it's finished, wanted cool space ship.

i found canvas shape instruction, creates flying saucer, , put inside draw() function --

ship.prototype.draw = function(ctx) {     ctx.fillstyle = this.color;     ctx.beginpath();     ctx.moveto(28.4, 16.9);     ctx.beziercurveto(28.4, 19.7, 22.9, 22.0, 16.0, 22.0);     ctx.beziercurveto(9.1, 22.0, 3.6, 19.7, 3.6, 16.9);     ctx.beziercurveto(3.6, 14.1, 9.1, 11.8, 16.0, 11.8);     ctx.beziercurveto(22.9, 11.8, 28.4, 14.1, 28.4, 16.9);     ctx.closepath();     ctx.fillstyle = "rgb(222, 103, 0)";     ctx.fill();      // draw saucer top.     ctx.beginpath();     ctx.moveto(22.3, 12.0);     ctx.beziercurveto(22.3, 13.3, 19.4, 14.3, 15.9, 14.3);     ctx.beziercurveto(12.4, 14.3, 9.6, 13.3, 9.6, 12.0);     ctx.beziercurveto(9.6, 10.8, 12.4, 9.7, 15.9, 9.7);     ctx.beziercurveto(19.4, 9.7, 22.3, 10.8, 22.3, 12.0);     ctx.closepath();     ctx.fillstyle = "rgb(51, 190, 0)";     ctx.fill();     } 

the ship has pos variable, array of x pos , y pos.

i'm confused heck though, in don't know apply pos[0] , pos[1] in drawing, make space ship render it's position currently.

help on super appreciated!

the simplest way in case translate canvas using position instead of re-calculating every point shape.

for example:

ship.prototype.draw = function(ctx, pos) {      ctx.translate(pos[0], pos[1]);  // translate      ctx.fillstyle = this.color;     ctx.beginpath();     ctx.moveto(28.4, 16.9);     ctx.beziercurveto(28.4, 19.7, 22.9, 22.0, 16.0, 22.0);     ctx.beziercurveto(9.1, 22.0, 3.6, 19.7, 3.6, 16.9);     ctx.beziercurveto(3.6, 14.1, 9.1, 11.8, 16.0, 11.8);     ctx.beziercurveto(22.9, 11.8, 28.4, 14.1, 28.4, 16.9);     ctx.closepath();     ctx.fillstyle = "rgb(222, 103, 0)";     ctx.fill();      // draw saucer top.     ctx.beginpath();     ctx.moveto(22.3, 12.0);     ctx.beziercurveto(22.3, 13.3, 19.4, 14.3, 15.9, 14.3);     ctx.beziercurveto(12.4, 14.3, 9.6, 13.3, 9.6, 12.0);     ctx.beziercurveto(9.6, 10.8, 12.4, 9.7, 15.9, 9.7);     ctx.beziercurveto(19.4, 9.7, 22.3, 10.8, 22.3, 12.0);     ctx.closepath();     ctx.fillstyle = "rgb(51, 190, 0)";     ctx.fill();      ctx.translate(-pos[0], -pos[1]);  // translate  } 

a tip render shape isolated off-screen canvas draw canvas main canvas using drawimage() (using off-screen canvas image). faster , easier maintain.


Comments

Popular posts from this blog

c# - How to get the current UAC mode -

postgresql - Lazarus + Postgres: incomplete startup packet -

javascript - Ajax jqXHR.status==0 fix error -