0

How do I go from drawing detached pixels on the canvas to rendering interactive entities?

My best guess is by adding event listeners to the constructors of self drawing objects, which cleverly add and remove further event listeners as necessary to any structure(s) on the screen.

I've tried the first step of this below, getting a single functioning even listener into the constructor, but it throws an exception.

As you may be able to determine yourself, I'd like this example to produce one or more entities in the canvas which can be clicked to log some kind of stat update message to the console. I can probably take it from there.

var game = document.getElementById( 'game' ),
    draw = game.getContext( '2d' );

var Hero = function(  ) {
  
      this.model = { pos: { x: 50, y: 50 }, dim: { x: 4, y: 4 } };
  
      this.draw_self = function(  ) {
        draw.fillRect( this.model.pos.x, this.model.pos.y, this.model.dim.x, this.model.dim.y );
      };
  
      this.update_self = function(  ) {
        /*...*/
      }
      
      this.draw_self(  );
  
      this.update_self(  );
  
      //  this.model.addEventListener( 'click', function( e ) { /*...*/ console.log( user + ' restored health.' ); } );
  
    };
    
var players = [  ];

players.push( new Hero(  ) ); 
canvas { box-shadow: 0 0 2px 0px black; }
<canvas id="game"></canvas>
Musixauce3000
  • 549
  • 1
  • 3
  • 11
  • You're going to have to define "interactive-entity". Because the canvas, at the end of the day, is separate pixels. You can draw images to the canvas, and you can do so with position information stored by whatever entity you want... but you can't add event listeners that apply just to that stretch, nor can you just pick up your drawn image and move it around on mousemove, or anything like that. Your codebase should be separating those things, and using an event or a polling loop to decide when to update, but leaving the how out of update handler. – Norguard Jun 22 '17 at 23:11
  • Though I can guess at what event polling is. I don't know much about code base or proper game loops. I typically just separate my draw from logic function and use requestanimationframe to loop those. I don't have enough experience to determine the pros or cons of any of that myself yet. As for the "interactive entity", think of a tower defense game. You have a bunch of little AI driven dudes coming your way, and no matter where they go on the canvas you can always interact with them using your mouse and other game structures. I can't imagine why the solution here isn't simple. – Musixauce3000 Jun 23 '17 at 12:25

0 Answers0