dangerChihuahua007
dangerChihuahua007

Reputation: 20925

Why can't I draw a rectangle in my HTML5 canvas?

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.

Upvotes: 1

Views: 5890

Answers (4)

Erica Web Girl
Erica Web Girl

Reputation: 11

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>

Upvotes: 0

Newbie
Newbie

Reputation: 21

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

Upvotes: 0

calebds
calebds

Reputation: 26238

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

Upvotes: 5

stewe
stewe

Reputation: 42654

Replace:

ctx.fillStyle("#f00");

with:

ctx.fillStyle="#f00";

Upvotes: 7

Related Questions