Reputation: 3371
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!
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
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