我试图通过在Javascript中制作一个Space Invader游戏来学习画布的使用。为了让它变得更加漂亮,我会拍摄一些(侵略者的)图像并尝试用画布染色。虽然IE和FireFox上的一切都很好,但是Chromes将画布的大小设置为0乘0而不是图像的大小。只有Chromes有这个问题并且是随机的。
以下是相关代码:
<!DOCTYPE html>
<html>
<head>
<title>Space Invaders</title>
<style>
img {
display : none;
}
</style>
<script>
<!--
function dyeImageWithColor(image, color, val) {
var canvas = document.createElement("canvas");
canvas.width = image.width;
canvas.height = image.height;
var ctx = canvas.getContext("2d");
ctx.globalAlpha = val;
ctx.fillStyle = color;
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.globalCompositeOperation = "destination-atop";
ctx.globalAlpha = 1;
ctx.drawImage(image, 0, 0);
return canvas;
}
//-->
</script>
</head>
<body>
<!-- These are basic images with transparency -->
<img src="./medias/si1.gif" id="si1" />
<img src="./medias/si2.gif" id="si2" />
<script type="text/javascript">
<!--
var enemy1 = document.getElementById("si1");
var enemy2 = document.getElementById("si2");
var enemies1 = [];
var enemies2 = [];
var colors = [];
for (var i = 0; i < 4; i++) {
var green = i * (255 / 4);
green -= green % 1;
colors[i] = "rgb(255, " + green + ", 00)";
enemies1[i] = dyeImageWithColor(enemy1, colors[i], 1);
enemies2[i] = dyeImageWithColor(enemy2, colors[i], 1);
}
console.log(enemies1);
console.log(enemies2);
//-->
</script>
</body>
</html>
在我的结尾,我看到IE和FireFox表现得很好,总是在我的数组中给我图像大小的画布。另一方面,Chromes经常将宽度和高度设置为0。