heyjohnmurray
heyjohnmurray

Reputation: 303

can't view html5 canvas contents on localhost

i have the following code in an html file and when i try to view the code on localhost [MAMP] all i see is a black canvas area with a border around it. i've checked it in chrome and firefox. same results. what am i doing wrong?

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8">
</head>
<body>      
    <canvas id="myCanvas" width="500" height="500" style="border:1px solid #000;"></canvas>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
    <script type="text/javascript">
        $(function() {
            var myCanvas = document.getElementById("myCanvas");
            var ctx = canvas.getContext("2d");
            ctx.fillRect(50, 50, 100, 100);
        //close jquery  
        });         
    </script>
</body>

Upvotes: 1

Views: 1710

Answers (2)

heyjohnmurray
heyjohnmurray

Reputation: 303

so i figured it out. thanks to Ken and Scott for their help.

var myCanvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillRect(50, 50, 100, 100);

should have been

var myCanvas = document.getElementById("myCanvas");
var ctx = myCanvas.getContext("2d"); //should have been myCanvas not canvas
ctx.fillRect(50, 50, 100, 100);

Upvotes: 4

Scott Mermelstein
Scott Mermelstein

Reputation: 15397

The default fill style of the canvas is black, while the canvas itself starts out as transparent. Set it to something else before calling fillRect, and you'll see better results.

ctx.fillStyle = "#F00"

Or, try this to see multiple rectangles:

var myCanvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "green";
ctx.fillRect(0, 0, myCanvas.width, myCanvas.height);
ctx.fillStyle = "red";
ctx.fillRect(50, 50, 100, 100);

FIDDLE

Upvotes: 3

Related Questions