0
タイトルが示すように、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");
}
}
});