Kevin Knapp
Kevin Knapp

Reputation: 53

Why window.onload works and onload="" does not work

So for some reason my canvas wasn't being applied when called through onload, I've tried other events and they work, I've tried changing where onload is placed (the footer, p and canvas tags) but that didn't work, and i tested the script functionality by placing it at the bottom outside of a function which does work

Ive tried another website which I did that had onload and canvas' and they work so after looking up possible solutions I ended up having to add windows.onload in the script area and it fixed it

What I would like to know is why doesn't the onload in the tags work

<!DOCTYPE html>

<html lang="en">
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<script>
function draw(){
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(17,17,15,0,2*Math.PI);
ctx.closePath();
ctx.lineWidth = 2;
ctx.fillStyle = 'yellow';
ctx.fill();
ctx.stroke();
}
window.onload= draw;
</script>
</head>

<footer>
<p>
<canvas id="canvas" width="34" height="34" onload="draw()"></canvas>
</p>
</footer>
</html>

Upvotes: 1

Views: 964

Answers (1)

Avinash Babu
Avinash Babu

Reputation: 6252

This is because only the body element and img element can fire the onload() event.

Just simply use the function name draw() inside the script tag like <script> draw(); </script> after the canvas tag..

Upvotes: 1

Related Questions