In my HTML I have:
<div id="cowcloud">
<canvas id="cows" width="1024" height="253">
<p>Browser doesn't support HTML5 canvas</p>
</canvas>
</div>
I load a javascript file doing some jQuery stuff in the section using the jQuery ready function. This has the following contents:
var cattle = [
{
"name" : "klara88",
"polygon" : {
"vertices": [
{"x" : "138", "y" : "204"},
{"x" : "145", "y" : "201"},
{"x" : "155", "y" : "178"},
{"x" : "208", "y" : "177"},
{"x" : "216", "y" : "200"},
{"x" : "208", "y" : "192"},
{"x" : "208", "y" : "218"},
{"x" : "196", "y" : "219"},
{"x" : "195", "y" : "206"},
{"x" : "170", "y" : "202"},
{"x" : "169", "y" : "219"},
{"x" : "150", "y" : "217"}
]
}
},
];
$(document).ready(function() {
$('#cowcloud').click(function(e){
[..]
/* Search the cattle */
$.each(cattle, function(i, cow) {
[..]
var context = $("#cows")[0].getContext('2d');
context.fillStyle = '#0f0';
context.beginPath();
$.each(cow.polygon.vertices, function(i, vertex) {
if(i == 0) {
context.moveTo(vertex.x, vertex.y);
}
else {
context.lineTo(vertex.x, vertex.y);
}
});
context.closePath();
context.fill();
});
});
});
I cut some code away that was not relevant to this question.
The strange thing is that even when using the document ready function, jQuery is unable to find the canvas with id ‘cows’. Also tried using plain javascript but then the element is null. Am I missing something here?
Ok this was a classical case of PEBKAC, in the code you didn’t see I had:
Which replaced the canvas.