The background image is not displaying in the HTML5 canvas animation

I am currently working on a simple animation project involving a bubble rising in a beer bottle. However, I am facing difficulties with the background image not displaying properly. When running the code, only the bubble animation is visible without the beer image.

Here is my code snippet:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8>
<link rel="stylesheet" type="text/css" href="style.css" />
<title>Beer Animation</title>
</head>

<body>


<div id="container">
<img class='img' src="https://i.imgur.com/VW3zcXq.jpg" alt="" />
<canvas id="beer" width="400" height="520" style="border:solid 1px">        
 </canvas>
</div>



<script type="text/javascript">


var c=document.getElementById("beer");
var ctx=c.getContext("2d");

var width = c.width;   // Size of Canvas
var heigth = c.height;
var x, y;              // Current x and y coordinates
var x0 = 50;           // Starting Coordinates
var y0 = 400;
var v0x = 0.05;        // Speed in Pixels/Millisecond
var v0y = 0.00005;
var dt = 20;           // Time Interval in Milliseconds
var r = 40;            // Radius
var time;              // Current Runtime
var i = 0;

draw(ctx);
var active = setInterval(function() {draw(ctx); }, dt);


function draw(context) {


    context.fillRect(0,0,width,heigth);
    
    context.fillStyle="#FFFFFF";   
    context.beginPath();
    context.arc(x, y, r, 0, Math.PI*2, true);
    context.closePath();
    context.stroke();

    x = x0 + v0x;                
    y = y0 + v0y - time;

    i += 0.1;
    time = i * dt;                      
    if (time >= 5000) {
        clearInterval(active)
    }

}

   </script>

</body>
   </html>

I have attempted to adjust the z-index, but it seems to be ineffective:

body{text-align: center;}
.img{position:absolute;z-index:-1;}

#container{
    display:inline-block;
    width: 400px;
    height:520px;
    margin: 0 auto;

    position:relative;
   }

#gameCanvas{
    position:relative;
z-index:20;
}

Any assistance would be greatly appreciated.

Answer №1

(I tend to provide responses in comments, but I realize it's better to answer directly here.)

By default, canvases are transparent, but you're currently wiping the canvas clean each time by filling it with white:

context.fillRect(0,0,width,height);

Rather than clearing it completely, consider erasing it (essentially filling it with a transparent color) so that elements behind the canvas remain visible:

context.clearRect(0,0,width,height);

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

Using ThreeJS in an iframe on a mobile device can lead to crashes in the browser due to multiple

I am encountering an issue with my ThreeJS based pages that are included via Iframe into other pages. The problem arises when switching between the two pages with ThreeJS Iframe on a mobile phone (specifically an iPhone 7 with just 1GB RAM). After two or ...

Sending an argument to a script's function

As a newcomer in this field, I appreciate your patience. Despite my efforts to find a solution to my problem, I have come up empty-handed. Below is the code in question: In the head <script> function ledonoff(led) { if (document.getElem ...

Ember.js issue: An 'id' is required for any object passed to the 'push' method

The data returned by the REST API I am working with does not have the expected JSON format for Ember.js. The data lacks id values like this: [{"objectID":"340907","owner":"Lokesh"},{"objectID":"340908","owner":"Cherukuri"}] To address this issue, I creat ...

Trouble importing the Node module

After diligently following the documentation on NPM site for a third party nodejs module, I encountered an error when executing a JS script with Node. The error message indicated that the node module was not found. The specific node-module being used is ...

Employ Selenium WebDriver to choose a radio button by its text label

The outdated radio button implementation on a legacy page is causing some trouble. Here's the current setup: <input id="button1" name="button" value="32" onchange="assignProduct(this.value);" type="radio"></input> RADIO TEXT 1 <input i ...

Transfer a single property from a particular object in one array to another array of objects based on a condition (JavaScript ES6)

I have 2 sets of data arrays coming from 2 separate API calls const data1 = [ { name: 'John', age: 30, id: 1, }, { name: 'Sarah', age: 28, id: 2, }, ]; const data2 = [ { status: 'active', ...

Is it possible to send an array value from JavaScript Ajax to PHP and then successfully retrieve and read it?

As a newcomer to PHP, I am facing a challenge in saving multiple values that increase dynamically. I'm passing an array value using the following method from my JavaScript code. $(".dyimei").each(function(i,value){ if($(this).val()=="") ...

Alter caret appearance in Bootstrap 4 when dropdown is clicked

Struggling with Bootstrap 4, I aim to craft a dropdown including a caret that points right by default. Upon clicking the dropdown, the caret direction should switch to pointing down. I discovered a method to achieve this /*For complete code details, plea ...

D3.js is providing inaccurate tick numbers

Even though I specify that I want 3 ticks, I end up with 4 in my d3 js code The y-axis values I am working with are [2, 1, 3, 2, 4, 4, 6] svg .select(`[data-labels-y]`) .call(d3.axisLeft().scale(yScale).ticks(3).tickPadding(4))` My expected tick valu ...

Having trouble with a React flow error that says the module is not a polymorphic type? Learn how to properly extend a class to

I'm currently working on expanding my current layout by attempting to override the renderHeader() method, but I'm encountering an issue with flow: The module ./Layout [1] does not qualify as a polymorphic type. Any suggestions on how to reso ...

The functionality of ellipsis, which consists of three dots, allows the text to expand

I am trying to implement a feature where the extra text is represented by three dots (...) as an ellipsis, and upon clicking the dots, the text should expand and contract. However, the current code only contracts the text and does not expand it upon clicki ...

Utilize AJAX to showcase JSON data retrieved from a specified URL

We are striving to showcase the names listed in our JSON file within a div using JavaScript. Despite multiple attempts, we have not yet achieved success. JSON data: This is the approach we took: <button>fetch data</button> <div id="result ...

Implementing conditional visibility of divs in HTML using Bootstrap 4 dropdown-menu selection

I am working on a dropdown menu bar with 3 options. When the user changes the selected option, I need to show or hide specific div elements accordingly. Can anyone provide guidance on how to achieve this using jQuery? <link rel="stylesheet" href="htt ...

Moving divs to a separate line in mobile display

I currently have a basic image-thumbnails landing page set up like this: <div style="display: inline-block;"><img style="margin: 3px 3px;" src="..." alt="" width="200" height="200" /></div> <div style="display: inline-block;"><i ...

Retrieving a complete array of countries from the mat-country-select package

I'm currently working with reactive forms in my Angular project and utilizing mat-country-select to display a list of countries in a select dropdown within my child FormComponent. <mat-select-country class="full-width" ...

What is the best method for encoding non-ASCII characters in JSON.stringify as ASCII-safe escaped characters (uXXXX) without the need for additional post-processing?

In order to send characters like ü to the server as unicode characters but in an ASCII-safe string format, I need them to be represented as \u00fc with 6 characters, rather than displaying the character itself. However, no matter what I try, after us ...

Necessary elements for communicating with an HTML form on the web

To fully comprehend the question, please take a look at the linked page below. Is there a method to identify the text input field for city/state/zip on the mentioned website? I am in need of allowing users to input city, state or zip into my own text fie ...

Steps for showing HTML code stored in a MongoDB field

I have a field in mongodb where I stored some HTML code. My issue is that when I retrieve it and display it inside <%= %>, it only shows the HTML code. I tried using eval() but it did not work. Here is an example of how I tried to display it in my .e ...

handlebars.js template to check the condition based on the last item in an array

I am currently utilizing handlebars.js as my templating engine and am interested in creating a conditional segment that will only display if it happens to be the final item within an array located in the templates configuration object. { columns: [{< ...

Comparing layout options: Tables vs Lists for user registration forms

I need to create a user registration form with a classic two-column layout, where labels are on the left and fields are on the right. The labels can be displayed in either English or French, resulting in varying label lengths. When it comes to structuring ...