正如标题所说,当我尝试绘制超过1张图像时,会发生一些奇怪的事情。虽然它确实以正确的尺寸在正确的位置绘制东西,但它最终只能使用最后绘制的图像。所以我最终在不同的位置和大小上获得相同的图像3次,而它们应该是不同的图像。
这是我的代码: HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>HTML5 Canvas</title>
<script src="jquery-3.2.1.js"></script>
<script src="main.js"></script>
</head>
<style>
#canvas:hover
{
/*cursor: none;*/
}
#canvas
{
}
body
{
margin: 0;
}
</style>
<body>
<form action="index.php" method="post" enctype="multipart/form-data">
<canvas id="canvas"></canvas>
</form>
</body>
</html>
使用Javascript:
$(document).ready(function(){
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
var keys = [];
var framerate = 1000/60;
var img = new Image();
var x = innerWidth/2 - 150;
var y = innerHeight/2 - 75;
var speed = 10;
var imageArray =
[
"sky.png",
"road.png",
"car.png"
];
function drawMap()
{
img.src = imageArray[0];
ctx.drawImage(img,0,0,innerWidth,innerHeight/2);
console.log("Sky Finished Drawing");
img.src = imageArray[1];
ctx.drawImage(img,0,innerHeight/2,innerWidth,innerHeight/2);
console.log("Road Finished Drawing");
img.src = imageArray[2];
ctx.drawImage(img,x,y,300,150);
console.log("Car Finished Drawing");
}
drawMap();
var mouse = {
x : undefined,
y : undefined
}
window.addEventListener("keydown",function(e){
keys[e.keyCode] = true;
});
window.addEventListener("keyup",function(e){
keys[e.keyCode] = false;
});
setInterval(animate,framerate);
function animate()
{
if(keys[87]) //W
{
ctx.clearRect(0,0,innerWidth,innerHeight);
drawMap();
console.log("W");
y -= speed;
}
if(keys[65]) //A
{
ctx.clearRect(0,0,innerWidth,innerHeight);
drawMap();
console.log("A");
x -= speed;
}
if(keys[83]) //S
{
ctx.clearRect(0,0,innerWidth,innerHeight);
drawMap();
console.log("S");
y += speed;
}
if(keys[68]) //D
{
ctx.clearRect(0,innerHeight/2,innerWidth,innerHeight);
drawMap();
x += speed;
console.log("D");
}
}
});
答案 0 :(得分:0)
您创建了一个Image对象,并为每个src使用了相同的一个,因此它仅应用了最后一个图像源。
请为每张图片创建Image对象:
function drawMap()
{
var img1 = new Image();
img1.src = imageArray[0];
ctx.drawImage(img1,0,0,innerWidth,innerHeight/2);
console.log("Sky Finished Drawing");
var img2 = new Image();
img2.src = imageArray[1];
ctx.drawImage(img2,0,innerHeight/2,innerWidth,innerHeight/2);
console.log("Road Finished Drawing");
var img3 = new Image();
img3.src = imageArray[2];
ctx.drawImage(img3,x,y,300,150);
console.log("Car Finished Drawing");
}