キャンバス上にある画像をクリックすると、メッセージが表示されるか、別の画像が表示されます(何らかのイベント)。なぜ私のコードがうまくいかないのか分かりません。誰か助けてくれますか?前もって感謝します!キャンバス上にある画像のイベントを作成する
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<style>
canvas {
border: 5px solid #d3d3d3;
background-color: #F08080;
}
</style>
</head>
<body onload="startGame()">
<script>
var backgroundMusic;
function startGame() {
myGameArea.start();
myPlayer = new component(300,300,"dort.png", 10, 120, "image");
backgroundMusic = new sound("panjabi.mp3")
backgroundMusic.play();
}
var myGameArea = {
canvas : document.createElement("canvas"),
start : function() {
this.canvas.width = 1200;
this.canvas.height = 700;
this.context = this.canvas.getContext("2d");
document.body.insertBefore(this.canvas, document.body.childNodes[0]);
this.interval = setInterval(updateGameArea, 20);
window.addEventListener('keydown', function(e) {
myGameArea.key = e.keyCode;
})
window.addEventListener('keyup', function(e){
myGameArea.key = false;
})
},
clear : function() {
this.context.clearRect(0,0,this.canvas.width,this.canvas.height);
}
}
function component(width, height, color, x, y, type) {
this.type = type;
if (type == "image") {
this.image = new Image();
this.image.src = color;
}
this.gamearea = myGameArea;
this.width = width;
this.height = height;
this.x = x;
this.y = y;
this.speedX = 0;
this.speedY = 0;
this.left = x
this.update = function() {
ctx = myGameArea.context;
if (type == "image") {
ctx.drawImage(this.image, this.x, this.y, this.width, this.height);
} else {
ctx.fillStyle = color;
ctx.fillRect(this.x, this.y, this.width, this.height); } }
this.newPos = function() {
this.x += this.speedX;
this.y += this.speedY;
}
}
function updateGameArea() {
myGameArea.clear();
myPlayer.speedX = 0;
myPlayer.speedY = 0;
if (myGameArea.key && myGameArea.key == 37) {myPlayer.speedX = -10}
if (myGameArea.key && myGameArea.key == 39) {myPlayer.speedX = 10}
if (myGameArea.key && myGameArea.key == 38) {myPlayer.speedY = -10}
if (myGameArea.key && myGameArea.key == 40) {myPlayer.speedY = 10}
myPlayer.newPos();
myPlayer.update();
}
function sound(src) {
this.sound = document.createElement("audio");
this.sound.src = src;
this.sound.setAttribute("preload", "auto");
this.sound.setAttribute("controls", "none");
this.sound.style.display = "none";
document.body.appendChild(this.sound);
this.play = function() {
this.sound.play();
}
this.stop = function(){
this.sound.pause();
}
}
$('#canvas').click(function (e) {
var clickedX = e.pageX - this.offsetLeft;
var clickedY = e.pageY - this.offsetTop;
for(var i = 0; i < myPlayer[i].length; i++) {
if(clickedX < myPlayer[i].right && clickedX > myPlayer[i].left &&
clickedY > myPlayer[i].top && clickedY < myPlayer[i].bottom) {
alert('clicked number');
}
}
});
</script>
</body>
</html>
"機能しません"とはどういう意味ですか?私が見ることの1つは、 'image.onload'で完全にロードする時間を与えずに' this.image'を描画しようとしていることです。 – markE