David C. David C. - 3 months ago 7
HTML Question

I'm trying to make a canvas on my page but it isn't working

This is my code:
I don't think the

<head>
<html>
and
<body>
parts were relevant to my problem. The
<head>
just contained a link to a CSS file.
I was trying to put a canvas into my page but for some reason nothing shows up. Can someone look at my code and see if something is making it not work?

<div id="title">
<h1 class="main">Options</h1>
</div>
<div id="field">
<p>
<div id="rad">
<input type="radio" name="bookmarks" value="ab" checked="checked"> All bookmarks<br>
<input type="radio" name="bookmarks" value="ao"> One folder<br>
</div>
<input id="input" type="text" value="Bookmark folder name">

<br>

<button onClick="setname(null);" id="sub">Submit</button>
</p>
</div>
<canvas id="myCanvas" width="400" height="500">
Your browser does not support the HTML5 canvas tag.
</canvas>

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "#000000";
ctx.fillRect(9,9,9,9);
</script>


Screenshot:
imgur

Answer

Your script code is executing before the canvas has been fully loaded.

Use window.onload to wait for the canvas to load:

<script>
    window.onload=(function(){
        var c = document.getElementById("myCanvas");
        var ctx = c.getContext("2d");
        ctx.fillStyle = "#000000";
        ctx.fillRect(9,9,9,9);
    });
</script>