title: Drawing Images on Canvas Using Node.js and EJS
body: <p>So, I'm new to Node and building a practice website where a user can sign in and create a chatroom anywhere on a campus map or join an existing chat room.  I've got my Mongo schema etc working.  Just having a little trouble rendering my models the way I want to.</p>
  
  <p>Basically, I'm trying to use canvas to first draw the map and then draw location pointers for all the existing chatrooms.  </p>
  
  <p>Here's my controller:</p>
  
  <pre><code>var db = require('../models')
  
  module.exports = function(req, res) {
  // finds all the current chatrooms and passes them to the
  // the campus map to be rendered
  db.Chatroom.find().exec(function(err, chatrooms) {
      if (err) throw err;
  
      res.render('map.ejs', { title: "Campus Map", chatrooms : chatrooms })
  });
  };
  </code></pre>
  
  <p>And here's my view:</p>
  
  <pre><code>&lt;% include header.ejs %&gt;
  
  &lt;script type="text/javascript"&gt;
      var images = {};
  
      /*
      Pre-loads the images so they can be drawn in order.
      */
      function loadImages() {
          var sources = ["campus_map.png", "icon.png"]
          var loadedImages = 0;
  
          for (var src in sources) {
              images[src] = new Image();
              images[src].onload = function() {
                  if(++loadedImages &gt;= 2) {
                      drawImages();
                  }
              };
              images[src].src = sources[src];
          }
      }
  
      /*
      Draws the map and all the current chatroom locations onto the canvas.
      */
      function drawImages() {
          var canvas = document.getElementById('canvas');
          var ctx = canvas.getContext('2d');
  
          ctx.canvas.width = window.innerWidth;
          ctx.canvas.height = window.innerHeight;
  
          ctx.drawImage(images[0], 0, 0, window.innerWidth, window.innerHeight);
  
          chatrooms.forEach(function(chatroom) { 
          ctx.drawImage(images[1], chatroom.x_coordinate + 10, chatroom.y_coordinate + 20, 20, 20);
          }
      }
      &lt;/script&gt;
  &lt;/head&gt;
  
  &lt;body onload="loadImages();"&gt;
      &lt;canvas id="canvas"&gt;&lt;/canvas&gt;
  
  &lt;% include footer.ejs %&gt;
  </code></pre>
  
  <p>I think my issue is that I'm trying to access the context passed to the view by my controller (chatrooms) in a script block in my head, but I don't really know how to get around this.</p>
  
  <p>Any guidance would be much appreciated!  Thanks.</p>