无法弄清楚如何让css / js屏蔽代码在meteor中工作

时间:2016-03-07 04:28:43

标签: javascript jquery html meteor image-masking

我找到了example code,我觉得很好,我只需插上它,但我是Meteor的新手,我希望只是犯了简单的天真错误。我认为jquery已经包含在Meteor中,如果我在" Client"中使用$或document.getElementById它可以工作的代码部分,但是我为后者得到一个null并且没有为前者定义$ :(

我试着用这篇文章中的代码尽可能简洁。

以下是我项目中屏蔽的javascript代码:

 if (Meteor.isClient) {

  var canvas = document.getElementById("canvas");;
  if (canvas[0].getContext) {
      var context = $canvas[0].getContext('2d');
      context.fillStyle = 'red';
      context.fillRect(10, 10, 300, 60);
  }
}

以下是相关的css代码:

#box {
    width: 150px;
    height: 150px;
    background-color: blue;
    border-radius: 50px;
    overflow: hidden;
    -webkit-mask-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAA5JREFUeNpiYGBgAAgwAAAEAAGbA+oJAAAAAElFTkSuQmCC); /* this fixes the overflow:hidden in Chrome/Opera */
}

html代码:

<template name="applicationLayout">
<div id = "backgroundDiv">
</div>

<div id="box">
  <canvas id="canvas" width="300px" height="300px"></canvas>
</div>
<div style="width: 40%">
  <header>
      {{> logoFloat}}
      {{> navbar}}
  </header>
  {{> yield}}
  {{> footer}}
</div>

更新我能够通过使用Salman的Template.applicationLayout.onRendered()函数然后使用anomepani javascript dom选择器代码并添加id =&#34;来实现此功能。画布&#34;到我的画布对象。谢谢你们的帮助,我希望我能把它们都标记为答案。

2 个答案:

答案 0 :(得分:2)

You need to wrap up your client code in onRendered method

if (Meteor.isClient) {
    Template.applicationLayout.onRendered(function(){
        var $canvas = document.getElementById("canvas");
        if (canvas[0].getContext) {
            var context = $canvas[0].getContext('2d');
            context.fillStyle = 'red';
            context.fillRect(10, 10, 300, 60);
        }
    });
}

答案 1 :(得分:1)

您已经复制了Example code中的代码,但是您混淆了jQuery选择器和javascript DOM选择器,这就是它无法正常工作的原因

使用javascript dom选择器尝试这个

var canvas = document.getElementById("canvas");;
  if (canvas.getContext) {
      var context = canvas.getContext('2d');
      context.fillStyle = 'red';
      context.fillRect(10, 10, 300, 60);
  }

或使用jQuery选择器

尝试这个
      var $canvas = $("#canvas");
        //you can create variable canvas instead '$canvas' both works
      if ($canvas[0].getContext) {
          var context = $canvas[0].getContext('2d');
          context.fillStyle = 'red';
          context.fillRect(10, 10, 300, 60);
      }