1

I am trying to draw a red rectangle on 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 the page blank? Chrome Web Developer Console issues no errors.

Rami Assi
  • 910
  • 2
  • 10
  • 19
dangerChihuahua007
  • 20,299
  • 35
  • 117
  • 206
  • 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/ – gen_Eric 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

4 Answers4

7

Replace:

ctx.fillStyle("#f00");

with:

ctx.fillStyle="#f00";

stewe
  • 41,820
  • 13
  • 79
  • 75
5

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

calebds
  • 25,670
  • 9
  • 46
  • 74
  • 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
0

Replacectx.fillStyle('#f00'); to ctx.fillStyle = 'red'; because fillStyle is a variable and NOT the function.

Newbie
  • 23
  • 4
0

I've been having issues all morning with javascript not drawing my shapes. Turns out you HAVE to set the width and height on the canvas tag in HTML, and not through the CSS, or the shapes will not draw.

example:

<canvas id="map" width="500" height="500"></canvas>