Iterate through Array drawing canvas Objects with each iteration

Hi guys,

Its the first time I’ve used HTML5 and I need multiple canvas items. I can’t draw them all on one canvas because it is the price bubble on a eCommerce CMS, therefore I have to iterate through an array drawing a canvas for each new product.

At the moment the code runs but only draws one canvas and I can’t work out why. I am using JQuery each() to go through each product and wish to draw a new circle on each one.

Check out my code below:


 var i = 0;
 var c = new Array();;
  var ctx = new Array();
if (isCanvasSupported())
{

$('.wrap_link').each(function() {
   $('<canvas id="html5_price" width="200" height="100"></canvas>').appendTo($(this));
   i++;
   console.log(i);
  c[i]= document.getElementById("html5_price");
  ctx[i]=c[i].getContext("2d");
ctx[i].fillStyle="#FF0000";
ctx[i].beginPath();
ctx[i].arc(70,18,15,0,Math.PI*2,true);
ctx[i].closePath();
ctx[i].fill();
});
}


Your code is indeed creating multiple canvas elements but using an id is what’s causing the drawing stage to fail as the document.getElementById method as far as I’m aware selects only the first element with the id specified, to avoid this see the below which should work fine:

var i = 0, c = [], ctx = [];

if (isCanvasSupported()) {
    $('.wrap_link').each(function() {
        var canvas = 'html5_price_' + i;

        $('<canvas />', {
            height : 100,
            id     : canvas,
            width  : 200
        }).appendTo($(this));

        c[i]   = document.getElementById(canvas);
        ctx[i] = c[i].getContext('2d');

        ctx[i].fillStyle = '#ff0000';
        ctx[i].beginPath();
        ctx[i].arc(70, 18, 15, 0, Math.PI * 2, true);
        ctx[i].closePath();
        ctx[i].fill();

        i++;
    });
}

It appears you are [re]defining the “html5_price” ID multiple times; again with each iteration.
An ID must be unique on a page.

You could try appending an “index” to the ID
“html5_price_1”, “html5_price_2”, etc.

OK thats great thanks for pointing out my mistake :wink: