为什么我把new Image()放在function里面时,图片出不来。
<!DOCTYPE html>
<html>
<head>
<meta charset="{CHARSET}">
<title></title>
</head>
<body onload="init()">
<canvas id="girl"></canvas>
</body>
<script>
var girl = document.getElementById("girl");
var girlWidth = 800;
var girlHeight = 400;
girl.width = girlWidth;
girl.height = girlHeight;
var girlCans = girl.getContext('2d');
function init(){
drawGirl();
}
function drawGirl(){
var girlPic = new Image();
girlPic.src = "img/girl.jpg";
girlCans.drawImage(girlPic,0,0, girlWidth, girlHeight);
}
</script>
</html>
然而我把girlPic设为全局的就能正常显示
<!DOCTYPE html>
<html>
<head>
<meta charset="{CHARSET}">
<title></title>
</head>
<body onload="init()">
<canvas id="girl"></canvas>
</body>
<script>
var girl = document.getElementById("girl");
var girlWidth = 800;
var girlHeight = 400;
girl.width = girlWidth;
girl.height = girlHeight;
var girlCans = girl.getContext('2d');
var girlPic = new Image();
girlPic.src = "img/girl.jpg";
function init(){
drawGirl();
}
function drawGirl(){
girlCans.drawImage(girlPic,0,0, girlWidth, girlHeight);
}
</script>
</html>
怪我咯2017-04-17 13:18:29
Because it takes a certain amount of time to load the image after src
is set. When the src
function is run immediately after drawImage
is set, image
actually has nothing. The more appropriate way to write
is image.onload = girlCans.drawImage(girlPic,0,0, girlWidth, girlHeight);