javascript - Is it possible to draw on the canvas from inside an object function? -
i've created object in javascript holds data needed context.drawimage(). possible call values , run context.drawimage() inside object function?
world = new sprite(0, 0, 100, 100, 0.4, 0, 0, 0); world.draw(); function sprite(spritex, spritey, spritew, spriteh, scale, positionx, positiony, direction) { this.imagepath = world_sprite; this.spritex = spritex; this.spritey = spritey; this.spritew = spritew; this.spriteh = spriteh; this.scale = scale; this.positionx = positionx; this.positiony = positiony; this.direction = direction; this.speed = 5; this.nogravity = false; this.direction = 0; //physics stuff this.velx = 0; this.vely = 0; this.friction = 0.98; }; sprite.prototype.draw = function() { context.drawimage(this.imagepath, this.spritex, this.spritey, this.spritew, this.spriteh, this.positionx, this.positiony, this.spritew * this.scale, this.spriteh * this.scale); };
yes, of course can draw on canvas inside object function...
this code has problem:
var world_sprite=new image(); world_sprite.src='someimage.png'; // next line executed early! // code attempts (fails) drawimage world_sprite // because has not loaded yet world = new sprite(0, 0, 100, 100, 0.4, 0, 0, 0); world.draw();
the browser loads images asynchronously. in above code, line after world_sprite.src='someimage.png'
executed before image loaded.
you need give new image
s time load using onload
callback.
var world_sprite=new image(); world_sprite.onload=function(){ alert('i displayed when world_sprite loaded , ready used in `drawimage`); }; world_sprite.src='someimage.png';
so use onload
in code this:
// create sprite "class" function sprite(spritex, spritey, spritew, spriteh, scale, positionx, positiony, direction){ this.imagepath = world_sprite; this.spritex = spritex; this.spritey = spritey; this.spritew = spritew; this.spriteh = spriteh; this.scale = scale; this.positionx = positionx; this.positiony = positiony; this.direction = direction; this.speed = 5; this.nogravity = false; this.direction = 0; //physics stuff this.velx = 0; this.vely = 0; this.friction = 0.98; }; sprite.prototype.draw = function(){ context.drawimage(this.imagepath, this.spritex, this.spritey, this.spritew, this.spriteh, this.positionx, this.positiony, this.spritew * this.scale, this.spriteh * this.scale); }; // create , load world_sprite var world_sprite=new image(); world_sprite.onload=function(){ // world_sprite loaded , // ready used in drawimage. // create new sprite , .draw() world = new sprite(0, 0, 100, 100, 0.4, 0, 0, 0); world.draw(); }; world_sprite.src='someimage.png';
Comments
Post a Comment