我正在尝试将图片放入我的网页,但是当我点击刷新按钮时,图像会一直消失。我检查了其他SO问题,其中提到我们必须添加一行名为window.onload=yourDrawFunction()
,我做了,但我仍然有问题。这是我的代码。
<!DOCTYPE html>
<html>
<head>
<title>Transformation Demo</title>
<style type="text/css">
.hidden{
display: none;
}
</style>
</head>
<body>
<h1>Tranformation Demo</h1>
<img class = "hidden" id="goku" width="220" height="277" src="goku.jpg" alt="Goku Pic">
<canvas id="surface" width=400 height=400>
Your browser doesn't support canvas tag.
</canvas>
<script>
function draw(){
var drawing=document.getElementById("surface");
var con=drawing.getContext("2d");
var gokupic=document.getElementById("goku");
con.save();
con.translate(100,100);
con.rotate(Math.PI / 4);
con.scale(3.0,1.5);
con.drawImage(gokupic, -25,-25,50,50);
con.restore();
con.strokeStyle="red";
con.lineWidth=5;
con.strokeRect(0,0,200,200);
}
window.onload=draw();
</script>
</body>
</html>
由于
注意:我的图像没有任何问题,但如果我只是这样做,这完全正常。
window.onload=function(){
...
...
...
...}
而不是给我的函数一个名为draw的名称然后调用它。那么为什么这有效呢?为什么我的draw()函数不起作用?
答案 0 :(得分:0)
以下是解释,window.onload = someFunction()
无效的原因,window.onload = someFunction
有效。
window.onload = someFunction()
将“onload”变量设置为调用someFunction的结果。除非“someFunction”本身返回一个函数,否则这可能不是你想要做的。
默认情况下,使用单个“event”参数调用onload函数。如果你想传递参数,你可能会做这样的事情:
window.onload = function (event) {
someFunction(someArg, someOtherArg)
}
有关详细信息,请参阅此link