Creating a JavaScript function to display an object on top of a background image

I am in the process of designing a program that mimics Guitar Hero, where red circles appear over an image of a violin when specific key presses are detected. However, I am encountering difficulties with making the circles appear on top of the image even after writing the necessary code following the canvas code. Can anyone provide guidance on how to achieve this? Additionally, I would like the red circles to disappear after some time, but using timeout alone is not sufficient since the image is not uniformly colored. Is there a way to change the color of the circles to match the background after a certain period?

<html>
    <head>
        <title>Violin Hero</title>
        <canvas id="myCanvas" width="1024" height="768"></canvas>
        <style>
            body {
                background-image: url("violin.jpg");
                background-size: 2500px 1300px;

            } 
        </style>
    </head>
    <body>  
        <canvas id="myCanvas" width="1024" height="768"></canvas>
        <img id="bow" src="bow.jpg" style="display:none;" />

        <script>
            var canvas = document.getElementById("myCanvas");
            var ctx = canvas.getContext("2d");

            window.addEventListener("keydown", soundPlay);
            function fillRed() {
                ctx.fillStyle = "red";
                ctx.fill();
            }

            function keyQ(){
                ctx.beginPath();
                ctx.arc(1200, 300, 15, 0,   Math.PI*2);
                ctx.fillStyle = "red";
                ctx.fill();
            }

            function keyW(){
                ctx.beginPath();
                ctx.arc(300, 300, 15, 0,    Math.PI*2);
                ctx.fillStyle = "red";
                ctx.fill();
            }

            function keyE(){
                ctx.beginPath();
                ctx.arc(900, 500, 15, 0,    Math.PI*2);
                ctx.fillStyle = "red";
                ctx.fill();
            }

            function keyR(){
                ctx.beginPath();
                ctx.arc(950, 100, 15, 0, Math.PI*2);
                ctx.fillStyle = "red";
                ctx.fill();
            }


            //var x = event.keyCode;

            //<input type="text" onkeydown="pressedKey(event)"> 

            function soundPlay(event) {
                var x = event.keyCode;

                if (x == 27) {  // 27 is the ESC key
                    alert ("You pressed the Escape key!");
                }
                else if (x == 81) {
                    keyQ();   
                    var sound = new Audio('1.mp3');
                    sound.play();
                    setTimeout(fillRed, 200);
                }
                else if (event.keyCode == 87) {
                    keyW();
                    var sound = new Audio("2.mp3");
                    sound.play();
                    setTimeout(fillRed, 200);
                }
                else if (event.keyCode == 69) {
                    keyE();
                    var sound = new Audio("3.mp3");
                    sound.play();
                    setTimeout(fillRed, 200);
                }
                else if (event.keyCode == 82) {
                    keyR();
                    var sound = new Audio("4.mp3");
                    sound.play();
                    setTimeout(fillRed, 200);
                }   
            }
        </script>
    </body>
</html>

Answer №1

If you want to bring something in front of images or always keep it behind other elements, you can achieve this using z-index in CSS. Create a CSS for a background image like the one below:

#backgroundImg{
position: absolute;
left: 0px;
top: 0px;
z-index: -1;
}

By setting the z-index to -1, the background image will always be positioned behind other elements. For more information, refer to this link or try out an example here.

If you have a second question, I recommend creating a new post and keeping this thread focused on addressing one issue at a time.

Answer №2

I have crafted a straightforward Plunkr demonstration to showcase how this type of feature can be accomplished in JavaScript.

Simply press s, a, or any other key to reveal a red dot on the screen.

<!DOCTYPE html>
<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

  <body id='mybody'>
    <img id='violin' src='http://cdn.shopify.com/s/files/1/0704/3831/products/Antoni_Debut_Violin_Outfit_3677b25a-7618-46f7-9313-6080c2a51e27_grande.jpg?v=1444483336'>
    <script>
      document.addEventListener('keydown', (event) => {
        console.log(event);
        if (event.key.toLowerCase() === 's') {
          showRedDot(110, 420);
        } else if (event.key.toLowerCase() === 'a') {
          showRedDot(150, 350);
        } else {
          showRedDot(200, 300);
        }
      });

      var showRedDot = (top, left) => {
        var oldDot = document.getElementById('redDot');
        if (oldDot) {
          oldDot.remove();
        }
        var dot = document.createElement('DIV');
        dot.id = 'redDot';
        dot.style.width = '10px';
        dot.style.height = '10px';
        dot.style.position = 'absolute';
        dot.style.borderRadius = '100%';
        dot.style.background = 'red';
        dot.style.top = top + 'px';
        dot.style.left = left + 'px';
        document.getElementById('mybody').appendChild(dot);
      };
    </script>
  </body>

</html>

Experience this functionality firsthand with this live Plunkr demo

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Accessing Beacon data through USB connection

My beacon employs the iBeacon protocol, which means I require assistance with two specific tasks: Firstly, I need to know how to read various data such as proximity UUID, major and minor values, transmit power, MAC address, etc., from the beacon by connec ...

How can I determine the width of a Bootstrap Column on a smartphone?

Currently, I am utilizing Photoshop to design a sequence of Wireframes for a forthcoming eCommerce website. I have a solid grasp on Bootstrap functioning based on a '12 column' structure, where the width of each column varies depending on the vi ...

Storing user input from HTML forms in a MySQL database table with PDO

Currently, I am in the process of developing a webpage that will contain multiple forms for users to fill out and submit. Once submitted, PHP will be responsible for executing a query to insert all the data into the table within their respective fields. I ...

Creating a customized SelectField component for Material-UI v1.0.0-alpha.21 with a fix for the Menu anchorEl problem

Currently, Material-UI v1.0.0 does not have a selectField implemented yet so I am attempting to create my own version using TextField, Menu, and MenuItem Components. Below is the code for my custom selectField: export default class SelectField extends Rea ...

What is causing my nested class to be treated as a sibling rather than a child in HTML code

I have been searching for a clear answer to my query, but haven't found one yet. In my HTML script, I have nested divs structured like this: <ul id="navbar"> <li><a href='#' class='dropdown'>Rules</a> ...

Tips for inserting a jQuery snippet into a universal file

Seeking some advice on integrating jQuery code into my JavaScript file, which is located at . The code snippet I am attempting to add looks like this: $(document).ready(function() { queue = new Object; queue.login = false; var $dialog = $ ...

Retrieve data from a REST API in a dynamic manner without manually specifying the table structure in the HTML code

I am looking to retrieve JSON data via a post request from a REST API: http://localhost/post1 param1='1' The response will look like this: { "json_table": [ { "date": 123, "test": "hello2" }, { "date": 19, ...

Strategies for efficiently updating specific objects within a state array by utilizing keys retrieved from the DOM

I am trying to figure out how to use the spread operator to update state arrays with objects that have specific ids. Currently, I have an array called "todos" containing objects like this: todos: [ { id: "1", description: "Run", co ...

Create a list using ng-repeat in AngularJS, each item separated by "custom categories"

I am looking to create a dynamic list that will display values entered by users, categorized by custom categories. The challenge is that I do not know in advance which category each element will belong to. Here's an example of how I envision the list ...

Storing information in a database with multiple entries

Displaying a list of inactive users from a mysqli database in a table format, each user has a row with three drop-down menu options - admin, delete user, and activate user. The table is populated using a prepared statement to fetch data from the database. ...

Enclose this within Stencil.js components

Is there a more efficient way to utilize a nested "this" in a Stencil.js component? Currently, I find myself following this approach: render() { let thisNested = this; return <Host> {this.images ? this.imagesArray.map(fu ...

CSS form not aligning properly within wrapper div and appears to be floating outside of it

I am in the process of creating a website that includes a wrapper div containing a: -Header -Content -Footer The issue I am encountering is when I insert regular text into the content section, everything displays properly and the background stretches s ...

VueJS does not support certain characters in its JavaScript replace function

In my current situation, I am utilizing the replace method in the following manner: <code v-html="'/<try>/'.replace(/(?:\r\n|\r|\n)/g, 'testing')"></code> As I work with a longer string t ...

What is the method for a mono social icon to function without requiring a specific class for each icon

Curious about the magic behind Mono Social Icons and how it effortlessly displays the correct icon. Unlike other font icon sets that require adding a class name to load a utf-8 character in :after, Mono Social Icons keeps it simple. Just add the icon as t ...

bash: The command "nodemon" could not be located

My experience with nodemon has been smooth for the past few months. However, today I encountered an error that I couldn't resolve. Despite uninstalling and reinstalling nodemon, as well as force installing it, I still received the same error message w ...

Tips for displaying HTML content using an array in Vue JS

Hi, I'm a beginner with Vue JS and I'm working on passing an HTML table using this array. I have a dropdown where I can select the option I want, but I'm struggling to figure out how to include HTML within it. Whenever I try, it ends up disp ...

Tips for delaying the loading of a video until after the initial page load in React/NextJS

I am looking to improve my lighthouse scores by delaying the loading of a video until after the page has completely loaded. Since the video is below the fold and only visible upon scrolling, I want it to wait for everything else on the page to load first i ...

Transforming text colors dynamically using Vue.js

Here is an Angular code snippet: <div [style.color]="'#' + prod.id.substring(0,6)"> <small>{{ prod.id }}</small> </div> Now I want to create a similar code using vue.js. ...

Get all instances of a particular attribute value within an interface

In my TypeScript code, I have defined an interface and two constants: interface Foo { readonly name: string; }; const FOO_1: Foo = { name: 'zing' }; const FOO_2: Foo = { name: 'baz' }; Is there a way to find all instances ...

Using Ajax.BeginForm with BeforeSend functionality

My MVC website has multiple Ajax.BeginForm elements, and I am looking to handle the beforeSend event of my Ajax calls. While the code below works for manual jquery ajax calls, it does not seem to work with the Ajax.BeginForm helpers: $.ajaxSetup({ &a ...