【问题标题】:Meteor: How to Get Context of an HTML5 Canvas ElementMeteor:如何获取 HTML5 Canvas 元素的上下文
【发布时间】:2014-10-30 21:18:30
【问题描述】:

尝试在 Meteor 中定义画布元素的上下文时,我收到以下错误: Uncaught TypeError: Cannot read property 'getContext' of undefined

如果我手动将 javascript 代码粘贴到 Chrome 的控制台中,它会按预期执行而没有错误。这告诉我 JS 代码在页面加载时没有正确执行(它是在设置画布元素之前执行的?)。我怎样才能解决这个问题?谢谢!


客户端模板: 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
});

【问题讨论】:

    标签: html canvas meteor


    【解决方案1】:

    问题是您试图在呈现之前访问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
    }
    

    【讨论】:

    • 就是这样!谢谢!
    猜你喜欢
    • 2011-04-04
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    • 2023-03-04
    • 1970-01-01
    • 2020-12-12
    • 2019-09-08
    • 1970-01-01
    相关资源
    最近更新 更多