1

I am trying to draw a red rectangle in my HTML5 canvas. Here is my HTML.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset=utf-8>
    <title>My Canvas Experiment</title>
    <link rel="stylesheet" type="text/css" href="main.css" />
    <script src="plotting.js"></script>
    <!--[if IE]>
      <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js">
      </script>
    <![endif]-->
  </head>
  <body>
    <canvas id="plot"></canvas>
  </body>
</html>

Here is plotting.js:

document.onload = function() {
    var c = document.getElementById("plot");
    var ctx = c.getContext("2d");
    ctx.fillStyle("#f00");
    ctx.fillRect(0, 0, 175, 40);
}

Here is main.css:

body { margin:100px; }

article, aside, figure, footer, header, hgroup, menu, nav, section { 
    display:block;
}

#plot {
    width: 500px;
    height: 400px;
}

Why is page blank? Chrome Web Developer Console issues no errors.

dangerChihuahua007
  • 18,433
  • 28
  • 104
  • 190
  • what do you see when you inspect the dom? You might want to try onready too... – hvgotcodes Mar 29 '12 at 17:58
  • I ran it in Chrome, and I saw an error in the console. `Uncaught TypeError: Property 'fillStyle' of object # is not a function`. http://jsfiddle.net/fhEjR/ – Rocket Hazmat Mar 29 '12 at 17:59
  • Thanks, but using `ctx.fillStyle = "#f00";` still doesn't make the rectangle appear. Neither does using `onready`. How do I inspect the DOM? – dangerChihuahua007 Mar 29 '12 at 18:00

2 Answers2

7

Replace:

ctx.fillStyle("#f00");

with:

ctx.fillStyle="#f00";

stewe
  • 39,054
  • 13
  • 75
  • 73
5

Use window.onload instead of document.onload, (keeping @stewe's suggestion).

calebds
  • 23,502
  • 7
  • 39
  • 73
  • Hey that did it! Thank you. The rectangle appears with `window.onload = function() { ...`. However, I am confused about why the window is ready after the document. – dangerChihuahua007 Mar 29 '12 at 18:04
  • 1
    Actually, this page cleared it up for me. http://stackoverflow.com/questions/588040/window-onload-vs-document-onload windows.onload fires when the page is ready for presentation, while document.onload fires when the DOM is ready. – dangerChihuahua007 Mar 29 '12 at 18:05