当试图在Meteor中定义canvas元素的上下文时,我收到以下错误:
Uncaught TypeError: Cannot read property 'getContext' of undefined
如果我手动将javascript代码粘贴到Chrome控制台中,它会按预期执行且没有错误。这告诉我JS代码在页面加载时没有正确执行(它在canvas元素设置之前执行?)。我怎样才能解决这个问题?谢谢!
<小时/> 客户端模板:
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>
客户端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
});
答案 0 :(得分:6)
问题是您在呈现之前尝试访问canvas
。
修正:
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
}