Jon Cursi
Jon Cursi

Reputation: 3371

Meteor: How to Get Context of an HTML5 Canvas Element

When trying to define the context of a canvas element within Meteor, I am receiving the following error: Uncaught TypeError: Cannot read property 'getContext' of undefined

If I manually paste the javascript code into Chrome's console, it executes as expected with no errors. This tells me that the JS code is not executing properly on page load (it is executing before the canvas element is set?). How can I fix this? Thanks!


The client-side template: client/views/test/test.html

<template name="test">
  <div class="container">
    <canvas id="canvas1">Your browser does not support HTML5 Canvas. Please update your browser to the latest version.</canvas>
  </div>
</template>

The client-side JS: client/views/test/test.js

$(window).load(function() {
    var canvas = $("#canvas1");
    canvas.css('width', $(window).innerWidth());
    canvas.css('height', $(window).innerHeight());
    var context = canvas[0].getContext('2d');
    // draw the canvas
});

Upvotes: 1

Views: 1780

Answers (1)

Kuba Wyrobek
Kuba Wyrobek

Reputation: 5273

The problem is that you are trying to access canvas before it is rendered.

Fix:

Template.test.rendered = function(){
    var canvas = $("#canvas1");
    canvas.css('width', $(window).innerWidth());
    canvas.css('height', $(window).innerHeight());
    var context = canvas[0].getContext('2d');
    // draw the canvas
}

Upvotes: 6

Related Questions