Search code examples
javascriptjqueryhtmlmeteorimage-masking

Cannot figure out how to get css/js masking code to work in meteor


I have found example code and I thought sweet I just have to plug it in, but I am new to Meteor and I am hopefully just making simple naive mistakes. I thought that jquery was already included in Meteor and that if I use $ or document.getElementById in the "Client" code section that it would work, but I either get a null for the latter and a $ is not defined for the former :(

I tried to be as concise as possible with my code in this post.

Here is the javascript code for the masking in my project:

 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);
  }
}

Here is the relevant css code:

#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 code:

<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>

UPDATE I was able to get this to work by using Salman's Template.applicationLayout.onRendered() function and then anomepani javascript dom selector code and by adding id="canvas" to my canvas object. Thank you guys for your help, I wish I could mark both as answers.


Solution

  • 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);
            }
        });
    }