Turk Turk - 5 months ago 15
HTML Question

Unable to display anything through Canvas

I am trying to build a highlighting library with JavaScript and jQuery. I am just diving into Canvasing techniques this week and did not find them to be all that difficult. However, while working today my code has simply stopped working. I know I am probably just missing something obvious but I have been stuck like this for almost 2 hours now and I need to get this project moving forward again. any help would be greatly appreciated.

$(function() {
$('area').click(function(event) {
document.getElementById("ctx").getContext("2d").fillStyle = "#FF0000";
document.getElementById("ctx").getContext("2d").fillRect(0, 0, 200, 200);
} );
} );

I have included my Javascript only since that is the only thing I have been changing recently.


Your code works for me, assuming:

  • The page has a clickable area.
  • The page has a canvas with an #id of ctx.

Make sure those 2 things are true about your setup...

Does your canvas element have an #id of ctx? That's not fatal, but the canvas element contains a context so it's a bit misleading.

If you have a canvas element like this:

<canvas id=canvas></canvas>

Then you can get a reusable reference to the canvas's context like this:

// no need to constantly get a context reference ...
//     just do it once at the start of your app
var canvas=document.getElementById('canvas');
var context=canvas.getContext('2d');

And you can reuse that context reference to do all your drawing calls: