Domanda

I'm completely new to Javascript and am trying to get the grips of how and when to call on a specific function.

My project is simple conceptually:

I want to be able to show an image and audio at the same time when a specific key is pressed. For example, if one presses "c", an image of a 'car' and a 'honk' sound will instantly appear onscreen (and disappear upon onkeyup).

Thank you.

È stato utile?

Soluzione

Warning: I'm not great at JavaScript programming and there are probably a lot of non-optimal practices in this example. However, this is the smallest example I could produce that does what you specified and will hopefully illustrate the basic concepts. Note that you need to put it in a directory that also has a picture of a car ("car.jpg") as well as a "honk.mp3" sound effect (I used this free sound).

Basic explanation: The body of the document registers key-down and key-up events and sets up a blank area for later drawing ("image-canvas" div tag). When a key is pressed, if it's the letter 'c', the JS code dynamically replaces the contents of the image canvas placeholder tag with an img tag referencing the the picture and an audio tag referencing the sound effect. When the 'c' key is released, the contents of the image canvas are erased.

Again, there are probably better, faster, more portable ways to accomplish this (probably with more code). But this is a simple example.

<!DOCTYPE html>
<html>

<head>
<script type="text/javascript">
function keyDown(event) {
  if (event.keyCode == 67) {
    var canvas = document.getElementById('image-canvas');
    canvas.innerHTML = '<img src="car.jpg" />'
    canvas.innerHTML += '<audio src="honk.mp3" autoplay="autoplay">'
  }
}
function keyUp(event) {
  if (event.keyCode == 67) {
    var canvas = document.getElementById('image-canvas');
    canvas.innerHTML = '';
  }
}
</script>
</head>

<body onkeydown="keyDown(event)" onkeyup="keyUp(event)">
<h1>Car!</h1>
<div id="image-canvas"></div>
</body>

</html>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top