Javascript 为什么Chrome返回的画布大小不正确
我试图通过用Javascript制作一个空间入侵者游戏来学习画布的使用。为了使它更华丽,我拍摄了一些入侵者的照片,并尝试用画布将它们染上。虽然IE和FireFox上的一切都很顺利,但Chromes将画布的大小改为0乘0,而不是图像的大小。只有Chromes有这个问题,并且会以随机间隔进行 以下是有关代码的详细信息:Javascript 为什么Chrome返回的画布大小不正确,javascript,google-chrome,canvas,random,size,Javascript,Google Chrome,Canvas,Random,Size,我试图通过用Javascript制作一个空间入侵者游戏来学习画布的使用。为了使它更华丽,我拍摄了一些入侵者的照片,并尝试用画布将它们染上。虽然IE和FireFox上的一切都很顺利,但Chromes将画布的大小改为0乘0,而不是图像的大小。只有Chromes有这个问题,并且会以随机间隔进行 以下是有关代码的详细信息: <!DOCTYPE html> <html> <head> <title>Space Invaders<
<!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>
太空入侵者
img{
显示:无;
}
在我这边,我看到IE和FireFox表现得很好,总是在我的阵列中给我图像大小的画布。另一方面,Chromes通常会将这些宽度和高度设置回0。您应该添加一个document.onload listener,并在加载文档时执行脚本,或者在javascript中加载带有对象图像的图像。事实上,我认为这可能是因为该函数是在图像尚未加载chrome时执行的,因此它们的大小值为0。非常感谢。document.onload侦听器工作正常。我想我不会很快犯这样的错误。顺便说一句——你不需要
,自从网景和IE版本3
——大约15年前以来,这些都是不需要的。任何时候我都会在教程网站看到它们,我认为它们是一个主要的红旗,它的信息在大多数时候是过时的,而且是完全错误的。