我正在尝试用Javascript创建一个扫雷板,但首先我试图只创建一个单元格。这是我的代码。我想从我创建的30px宽度和30px高度图片中绘制一个单元格(cell.png)但是当我运行代码时我只看到画布。我做错了什么?
<!DOCTYPE html>
<html>
<head>
<script>
var s = {
rows: 10,
col: 10,
width: 30,
height: 30,
};
var c;
window.onload = function(){
var canvas = document.getElementById("myCanvas");
c = canvas.getContext("2d");
// c.fillRect(50,50,300,300);
init();
}
var box;
function init(){
box = new Image();
box.src = "cell.png";
draw();
}
function draw(){
c.clearRect(0,0,400,400);
c.drawImage(box,10,10);
}
</script>
</head>
<body>
<div id="controls">
</div>
<div id="game">
<canvas id="myCanvas" width="400" height="400" style="border:1px solid #c3c3c3;">
</canvas>
</div>
</body>
</html>
&#13;
答案 0 :(得分:2)
您遇到的问题是因为您的代码在尝试绘制之前没有等待图像加载。您需要等到它被加载然后调用绘图代码,这可以通过图像的onload事件来完成
volatile
&#13;
var s = {
rows: 10,
col: 10,
width: 30,
height: 30,
};
var c;
window.onload = function(){
var canvas = document.getElementById("myCanvas");
c = canvas.getContext("2d");
init();
}
var box;
function init(){
box = new Image();
//onload will be called once the image has loaded
box.onload = function(){
//Here you call draw.
draw();
};
box.src = "http://placehold.it/30x30"; //"cell.png";
}
function draw(){
c.clearRect(0,0,400,400);
c.drawImage(box,10,10);
}
&#13;