How to add onclick event to play audio on canvas?

Asked

Viewed 2,654 times

2

By clicking on an image I want to perform a sound.

How can I do this function using the event onclick?

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();
}
  • 3

    Your question appears to be in English, did you want to post it on Stack Overflow in English? If your intention was to post it here in Stack Overflow, edit and translate your question.

  • 1

    @Chun, "apparently" is your kindness. She’s in English, rsrsrsrs

  • @Bruno Rhafael Could put your HTML code too?

1 answer

1

Hello,

Try to do it this way

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


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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.