How implement a canvas

I’ve been trying to implement a basic canvas for hours and not getting anywhere. Is this the right approach? Thanks!

docRender.js

Template.canvas.onRendered(function() {
  canvas = document.getElementById('canvas');
  context = canvas.getContext('2d');
  context.fillStyle = 'green';
  context.fillRect(10, 10, 200, 200);
});

docRender.html

<template name="docRender">
  {{>canvas}}
</template>

<template name="canvas">
  <div id='canvas'></div>
</template>

I am not an expert but I’ll try something like:

docRender.js

Template.canvas.onRendered(function() {
  canvas = document.getElementById('myCanvas');
  context = canvas.getContext('2d');
  context.fillStyle = 'green';
  context.fillRect(10, 10, 200, 200);
});

docRender.html

<template name="docRender">
{{>canvas}}
</template>

<template name="canvas">
<canvas id='myCanvas'></canvas>
</template>
2 Likes

You need to create an HTML canvas element. What you are currently doing here:

canvas = document.getElementById('canvas');

is getting the DOM id for a div element, whereas you need something like this in your template:

<template name="canvas">
  <canvas id='canvas'></canvas>
</template>

In my experience it’s also a good idea to explicitly set the width and height (or you can end up with a 0x0 canvas, which is a tad hard to see :wink:! Maybe add a class and some CSS, or do it in the JS, for example:

canvas = document.getElementById('canvas');
canvas.setAttribute('width', 400);
canvas.setAttribute('height', 300);

Edit: @PolGuixe :you beat me to it :smile:!

2 Likes

Oh no – not sure how I could miss that! :confused:

Thanks @PolGuixe and @robfallows. Setting up a canvas element solves the problem. And knowing how to set the canvas attributes in JS is helpful as well!

1 Like

I just started a new meteor app and am trying to get started using canvas so copied the above code into the main.html and the main.js files and do not get any results when viewed in Firefox. Am I missing something?

1 Like

I have the exact same issue, did you find a solution?