单击时添加addEventListener声音

时间:2015-12-13 18:20:19

标签: html5 audio canvas html5-audio

我想要做的是'addEventListener'功能。单击画布并显示雨滴时,会发出晃动声。所以无论你点击多少次,声音都会一直播放。

我不知道它叫什么,我的教授建议了。但是,当我梳理谷歌时,我发现的只是按钮点击或Jquery的东西。我不想要一个按钮,我不允许使用Jquery。

与往常一样,我只是朝着正确的方向努力。

感谢您迄今为止给予我的所有帮助。

var canvas;
var context;
var drops = [];
var squares = [];


function Drop(x,y,color){
    this.x = x;
    this.y = y;
    this.color = color;
    this.dy = Math.random();
}


function Square(x,y,w,color){
    this.sx = x;
    this.sy = y;
    this.sw = w;
    this.color = color;
    this.qy = Math.random();
}

function init(){
    canvas = document.getElementById('canvas');
    context = canvas.getContext('2d');

    alert("Hello!\nClick on the screen for rain drops!");

    window.addEventListener('resize', resizeCanvas, false);
    window.addEventListener('orientationchange', resizeCanvas, false);
    resizeCanvas();
    canvas.onclick = function(event){
        handleClick(event.clientX, event.clientY);
    };
    setInterval(handleClick,5);



}
function handleClick(x,y,w){
    var found = false;
    for(var i = 0; i<drops.length; i++){
        d = Math.sqrt((drops[i].x-x)*(drops[i].x-x) + (drops[i].y-y)*(drops[i].y-y));
        if(d<=5){
            drops.splice(i,1);
            found = true;
        }
}

    fillBackgroundColor();
    if(!found){
    var colors = ["#000080", "#add8e6", "blue"];
        var color = colors[Math.floor(Math.random()*colors.length)];
        drops.push(new Drop(x,y,color));
        squares.push(new Square(x,y,w,color));

    }

            for(var i = 0; i<drops.length; i++){
        drawDrop(drops[i]);
}
                for(var i = 0; i<squares.length; i++){
        drawSquare(squares[i]);
}

}


function drawDrop(drop){
    context.beginPath();
    context.arc(drop.x, drop.y, 5, 0, Math.PI);
    context.fillStyle = drop.color;
    context.moveTo(drop.x - 5, drop.y);
    context.lineTo(drop.x, drop.y - 7);
    context.lineTo(drop.x + 5, drop.y);
    context.closePath();
    context.fill();
    if (drop.y + drop.dy > canvas.height || drop.y + drop.dy < 0)
        drop.dy != -drop.dy;
    drop.y += drop.dy;
};


function drawSquare(square){
    var sw = Math.floor(4);
    var sx = Math.floor(Math.random() * canvas.width);
    var sy = Math.floor(Math.random() * canvas.height);
    context.beginPath();
    context.rect(sx, sy, sw, sw); 
    context.fillStyle = '#add8e6';
    context.fill();

};




function fillBackgroundColor(){
    context.fillStyle = 'gray';
    context.fillRect(0,0,canvas.width,canvas.height);
}
function resizeCanvas(){
    canvas.width = window.innerWidth - 20;
    canvas.height = window.innerHeight - 20;
    fillBackgroundColor();
    for(var i = 0; i<drops.length; i++){
        drawDrop(drops[i]);
    }

            for(var i = 0; i<squares.length; i++){
        drawSquare(squares[i]);
    }



}

function degreesToRadians(degrees) {
        return (degrees * Math.PI)/180;
    }
window.onload = init;

</script>
</head>
<body>
<canvas id='canvas' width=500 height=500></canvas>
</body>

1 个答案:

答案 0 :(得分:3)

单击画布或任何元素

要向画布添加事件监听器,您只需要该元素,您可以通过多种方式从DOM获取它,我使用了getElementById及其唯一ID。然后添加一个click事件,只需附加一个监听器和要调用的函数。

每次单击画布时都会调用pl​​aySound。

var canvas = document.getElementById("canvasID"); // get the canvas
canvas.addEventListener("click",playSound);   // call playSound when clicked
// See below for the function playSound

您还可以为mousedown和mouseup添加事件侦听器,因为只有在释放鼠标按钮时才会调用click,这可能不是所需的效果。

加载声音

由于需要加载声音并且可能需要一些时间,因此您需要有一种方法来指示声音已加载并准备播放。对于这个简单的答案,信号量就能解决问题。只需设置一个属性即可指示已加载。

var sound = new Audio();         // create the audio
sound.src = "SoundFileURL.mp3";  // set the resource location 
sound.oncanplaythrough = function(){   // When the sound has completely loaded
    sound.readyToRock = true;    // flag sound is ready to play
                                 // I just made it up and can be anything
};
sound.onerror = function(){      // not required but if there are problems this will help debug the problem
    console.log("Sound file SoundFileURL.mp3 failed to load.")
};

重复播放声音

playSound功能。音频资源只能作为一种声音播放。你无法在它自己的顶部播放它。重复单击时,您需要重置声音播放位置,以便再次启动。要执行此操作,只需将currentTime设置为0(声音的开头)并调用方法play。这样每次点击都会启动声音或倒带并重新开始,无需检查是否正在播放。如果你想要声音重叠,你需要加载它的几个副本,并循环你每次点击播放的那个。

// assuming sound is in scope from above code
function playSound(){
    if(sound && sound.readyToRock){  // check for the sound and if it has loaded
        sound.currentTime = 0;       // seek to the start
        sound.play();                // play it till it ends
    }
}

重叠声音

从阵列播放相同的声音,使其重叠。将相同的声音多次加载到数组中。保留一个变量,该变量将指向当用户调用该函数时播放的数组中的下一个声音(通过单击事件)然后寻找开始并播放声音。增加下一个声音指针,为下次点击做好准备。

这会让声音自我发挥。加载声音的次数取决于用户点击的频率和声音的持续时间。不要过分,因为有一点你无法判断新声音是否已经开始,或者是否重新开始播放。

多次加载相同的声音

var sounds = [];  // array to hold the sound
for(var i = 0; i < 4; i++){
    var sound = new Audio();         // create the audio
    sound.src = "SoundFileURL.mp3";  // set the resource location 
    sounds.push(sound);              // put the sound on the array
}

播放声音数组

// assuming that the array sounds has the sounds you want to overlap
// and that they have been loaded so there is no need to check their status
var soundToPlay = 0; // the next sound to play

// the click event function.
function playSound(){
    var sound = sounds[soundToPlay % sounds.length]; // get the next sound
                                                     // making sure that it 
                                                     // does not go past the 
                                                     // of the array
    sound.currentTime = 0; // seek to start
    sound.play();          // play it
    soundToPlay += 1;      // point to the next sound to play
}