简体   繁体   English

如何使声音响应js html canvas中的按键?

[英]How to make a sound respond to a key press in js html canvas?

I am making a canvas, one where you are a little ship and you shoot little pixels to destroy other little pixel ships. 我正在制作一幅画布,在其中您是一艘小飞船,并且您会射击小像素以摧毁其他小像素飞船。 I want to make it so that when you press the key that would make the ship shoot, it would also play a little "pew" sound. 我要这样做,以便当您按下可以使飞船射击的键时,它也可以播放一点““”声。 I have no idea how to add sounds or images for that matter. 我不知道如何为此添加声音或图像。 Please help. 请帮忙。

There is an audio tag in HTML. HTML中有一个音频标签。 Put any sounds you'll be using within the tag like so: 将您要使用的所有声音放入标记中,如下所示:

<audio>
<source id="pew" src="pew.mp3"></source>
</audio>

In Javascript, there is a standard method called play(): 在Javascript中,有一个称为play()的标准方法:

function playSound(){
    var sound = document.getElementById("pew");
    sound.play();
}

Call the function either in HTML or with JQuery: 用HTML或JQuery调用函数:

<input type="button" value="pew pew pew" onClick="playSound()">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM