0
EDITED問題和代碼:如果我現在在函數move_background()中使用return語句並將圖像保存在var imageObj中,仍然不工作,並且在內部和外部圖像時播放聲音(聲音3在外部畫布上正確播放時),任何想法爲什麼?畫布內部的圖像:區分onclick內部圖像和外部圖像(但畫布內部)
</script>
<canvas id="myCanvas" width="400" height="400" style="border:1px solid white;" onclick="myFunct()"></canvas>
<!-- audio source is specified later-->
<audio id="audio"></audio>
<style>
#myCanvas { position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin:auto; }
</style>
<script>
var canvas=document.getElementById("myCanvas");
context = canvas.getContext('2d');
var imageObj = make_background();
function make_background()
{
img = new Image();;
img.src="img.gif";
img.id = "myImage";
img.onload = function(){
context.drawImage(img, (canvas.width-img.width)/2, (canvas.height-img.height)/2);
}
return img
}
function play(){
var audio = document.getElementById("audio");
audio.play();
}
function myFunct() {
var audio = document.getElementById("audio");
// PLAY DIFFERENT SOUND IF ANSWER IS RIGHT OR WRONG
document.addEventListener("click", function(e){
if(e.target == imageObj){ // inside canvas and inside image
audio.src = "sound1.mp3";
audio.play();
}
else if (e.target === canvas && e.target !== imageObj) { // inside canvas but outside image
audio.src = "sound2.mp3";
audio.play();
}
else{
audio.src = "sound3.mp3";
audio.play();
}
// GENERATE RANDOM LOCATION
var x = Math.floor(Math.random()*300);
var y = Math.floor(Math.random()*300);
var obj = document.getElementById("myCanvas");
obj.style.top = x + "px";
obj.style.left = y + "px";
obj.style.bottom = x - "px";
obj.style.right = y - "px";
},false);
}
</script>
原問題和代碼:我有一個矩形畫布和一個圖像在它的中心。當點擊位於畫布內部(但在圖像之外)並且點擊位於圖像內部時,我想播放不同的音頻文件。 這是我現在
<canvas id="myCanvas" width="400" height="400" style="border:1px solid white;" onclick="myFunct()"></canvas>
<!-- audio source is specified later-->
<audio id="audio"></audio>
<script>
var canvas=document.getElementById("myCanvas");
context = canvas.getContext('2d');
make_background();
function make_background()
{
img = new Image();
img.src = 'img.gif';
img.onload = function(){
context.drawImage(img, 100, 100);
}
}
function play(){
var audio = document.getElementById("audio");
audio.play();
}
function myFunct() {
var audio = document.getElementById("audio");
var canv = document.getElementById("myCanvas");
document.addEventListener("click", function(e){
if(inside canvas and inside img){
audio.src = "sound1.mp3";
audio.play();
}
else if (inside canvas and outside img) {
audio.src = "sound2.mp3";
audio.play();
}
else{
audio.src = "sound3.mp3";
audio.play();
}
},false);
}
</script>
我試過了你的代碼,但是當我點擊畫布(外部和內部圖像)並且沒有聲音被播放時,播放聲音2似乎就被播放了。我想要多個點擊事件,因爲我每次點擊它時都會改變畫布的位置(因此我改變了圖像的位置)(在myFunct()內部我有: \t var x = Math.floor(Math.random()* 300); \t變種Y = Math.floor(的Math.random()* 300); \t VAR OBJ =的document.getElementById( 「myCanvas」); \t obj.style.top = X + 「像素」; \t obj.style.left = y +「px」; – Gigi