How to add onclick event to play audio on canvas?

2

When clicking on an image I want to play a sound.

How can I do this function using the onclick event?

Code:

window.onload = function myCanvas() {
                var c = document.getElementById("myCanvas");
                var ctx = c.getContext("2d");
                var img = document.getElementById("background");
                var img2 = document.getElementById("pedal1");

                ctx.drawImage(img,5,5);
                ctx.drawImage(img2,100,100);
}


function music()
{

    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");   
    var audio1 = new Audio();
    audio1.src = "audio/samples/F.mp3";
    audio1.play();
}
    
asked by anonymous 18.10.2015 / 22:55

1 answer

1

Hello,

Try to do so

<img src="" onclick="TocarMusica()" />


function TocarMusica(){
    var audio1 = new Audio();
    audio1.src = "audio/samples/F.mp3";
    audio1.play();
}
    
20.10.2015 / 15:14