Meteor:如何获取HTML5画布元素的上下文 [英] Meteor: How to Get Context of an HTML5 Canvas Element

查看:242
本文介绍了Meteor:如何获取HTML5画布元素的上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当试图在Meteor中定义一个canvas元素的上下文时,我收到以下错误:
未捕获的TypeError:无法读取未定义的属性'getContext'

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

如果我手动将JavaScript代码粘贴到Chrome的控制台,它会按预期执行,没有错误。这告诉我,JS代码在页面加载时没有正确执行(它在canvas元素设置之前执行)。如何解决这个问题?

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>

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


推荐答案

问题是你试图访问<$

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

修复:

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
}

这篇关于Meteor:如何获取HTML5画布元素的上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆