Why window.onload works and onload=“” does not work

北慕城南 提交于 2019-12-24 12:47:24

问题


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>

回答1:


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..



来源:https://stackoverflow.com/questions/27140026/why-window-onload-works-and-onload-does-not-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!