javascript - Canvas component constructor with the built-in image object doesn't show's the image -


i'm working canvas , try create constructor function 'component' create various elements. idea has have ability fill created element not color, background image. works fine filling element color, can't load image. no errors in console. it's nothing on screen. need help, please. whole code this:

var myrect;  function startgame (){     workingarea.create();     myrect = new component(30, 30, "grass.jpg", 10, 120, 'image'); }  var workingarea = {     canvas: document.createelement('canvas'),     create: function (){         this.canvas.width = 480;         this.canvas.height = 270;         this.context = this.canvas.getcontext('2d');         document.body.insertbefore(this.canvas, document.body.childnodes[0]);     } };   function component(width, height, color, x, y, type){     this.width = width;     this.height = height;     this.x = x;     this.y = y;     this.type = type;     if (this.type === 'image'){         this.image = new image();         this.image.src = color;     }     var ctx = workingarea.context;     if (type === 'image'){         this.image.onload = ctx.drawimage(this.image, this.x, this.y, this.width, this.height);     }     else{         ctx.fillstyle = color;         ctx.fillrect(this.x, this.y, this.width, this.height);     } }     }     else{         ctx.fillstyle = color;         ctx.fillrect(this.x, this.y, this.width, this.height);     } } 

see here how load image , paint on canvas: https://developer.mozilla.org/en-us/docs/web/api/canvas_api/tutorial/using_images#example_a_simple_line_graph

if interested, here explanation how access "this" inside callback: how access correct `this` context inside callback?

in case should like:

function component(width, height, color, x, y, type){   this.width = width;   this.height = height;   this.x = x;   this.y = y;   this.type = type;    var ctx = workingarea.context;   if (type === 'image') {     this.image = new image();     // async, need pass drawimage inside callback function     this.image.onload = function() {       ctx.drawimage(this.image, this.x, this.y, this.width, this.height);     }.bind(this); // bind "this" callback     this.image.src = color; // valid, unfortunate name color.   } else {     ctx.fillstyle = color;     ctx.fillrect(this.x, this.y, this.width, this.height);   } } 

Comments

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -