Meteor:如何获取HTML5 Canvas元素的上下文

时间:2014-09-05 21:10:03

标签: html5 canvas meteor

当试图在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
});

1 个答案:

答案 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
}