Incapable of stacking one canvas on top of another

I'm new to javascript and looking for help with positioning a canvas element behind another. The code I have may be a bit messy, so any assistance is greatly appreciated. My goal is to have the canvas named "myCanvas" appear behind "coinAnimation". Thank you in advance for any responses.

HTML

<div id="wrapper">
<canvas id="coinAnimation" height="500" width="500"></canvas>
<canvas id="myCanvas" height="500" width="600"></canvas>
</div>

Javascript

<script type="text/javascript">
(function () {
var coin,
    coinImage,
    canvas;                 

function gameLoop () {
    window.requestAnimationFrame(gameLoop);
    coin.update();
    coin.render();
    }

function sprite (options) {
var that = {},
frameIndex = 0,
    tickCount = 0,
    ticksPerFrame = options.ticksPerFrame || 0,
    numberOfFrames = options.numberOfFrames || 1;

    that.context = options.context;
    that.width = options.width;
    that.height = options.height;
    that.image = options.image;

    that.update = function () {

    tickCount += 1;

    if (tickCount > ticksPerFrame) {

    tickCount = 0;

// If the current frame index is in range
if (frameIndex < numberOfFrames - 1) {  

// Go to the next frame
frameIndex += 1;
} else {
frameIndex = 0;
}
}
};
that.render = function () {

// Clear the canvas
that.context.clearRect(0, 0, that.width, that.height);

// Draw the animation
that.context.drawImage(
    that.image,
    frameIndex * that.width / numberOfFrames,
    -110,
    that.width / numberOfFrames,
    that.height,
    0,
    0,
    that.width / numberOfFrames,
    that.height);
    };

return that;
}

// Get canvas
canvas = document.getElementById("coinAnimation");
canvas.width = 600;
canvas.height = 300;

// Create sprite sheet
coinImage = new Image();    

// Create sprite
coin = sprite({
    context: canvas.getContext("2d"),
    width: 1000,
    height: 300,
    image: coinImage,
    numberOfFrames: 10,
    ticksPerFrame: 7
    });

// Load sprite sheet
coinImage.addEventListener("load", gameLoop);
coinImage.src = "images/test2.png";

} ());
</script>

<script type="text/javascript">
window.addEventListener('load', function () {
  var
    img = new Image,
    ctx = document.getElementById('myCanvas').getContext('2d');

  img.src = "images/back.png";
  img.addEventListener('load', function () {

    var interval = setInterval(function() {
      var x = 0, y = 0;

      return function () {
        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
        ctx.drawImage(img, x, y);

        x += -1;
        if (x > ctx.canvas.width) {
          x = 0;
        }
      };
    }(), 1000/40);
  }, false);
}, false);
</script>

Answer №1

To view a demonstration of positioning and z-index, click on this link: jsfilddle.net.

Start by setting the wrapper div to position relative as the base for container divs. Then, set the container divs to position absolute at (0,0). Finally, adjust the z-index so that myCanvas is positioned behind coinAnimation.

CSS:

#wrapper
{
    position:relative;    
}

#coinAnimation
{
    background-color:blue; 
    position:absolute;
    z-index:1;
}
#myCanvas
{
    background-color:red;
    position:absolute;
    top:0px;
    left:0px;
    z-index:0;
}

HTML:

<div id="wrapper">
    <canvas id="coinAnimation" height="500" width="500"></canvas>
    <canvas id="myCanvas" height="500" width="600"></canvas>
</div>

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

In TypeScript, the function is failing to retrieve the complete array value

I'm facing an issue with a program that is supposed to piece together all the letters, but it's not functioning correctly. I've tried using the debugger, but it doesn't display any errors. Here's the code snippet: var phrase = [ &a ...

Utilizing React for incorporating HTML5 canvas gradients

I'm currently working on an app that allows users to generate a background gradient with two distinct colors using React. The issue I'm facing is that while the first color appears correctly, the second color ends up looking more like a solid col ...

Tips for optimizing the "framerate" (setInterval delay) in a JavaScript animation loop

When creating a JavaScript animation, it's common practice to use setInterval (or multiple setTimeouts) to create a loop. But what is the optimal delay to set in these setInterval/setTimeout calls? In the jQuery API page for the .animate() function, ...

What is the best way to animate specific table data within a table row using ng-animate?

Are you working with Angular's ng-repeat to display a table with multiple rows? Do you wish to add an animation effect to specific cells when a user hovers over a row in the table? In the scenario outlined below, the goal is to have only certain cell ...

Implementing SweetAlert2 in Vue.js to create a modal prompt for confirmation prior to deleting an item

I'm encountering an issue with sweetalert2 while using Laravel Vue for my app development. My goal is to have a confirmation modal pop-up when deleting a row from the database. However, whenever I click "Yes", the item is successfully removed. But if ...

Unlock a multitude of outcomes with Sequelize

Is there a way to retrieve multiple results from Sequelize and store them in an array? For example, I want to fetch all the values in the name field from the test table and display them in the console. This is what I tried: test.findAll().them(function(re ...

Fastify route handler failing to start after onRequest hook is executed

I am currently working on a fastify application that needs to capture the raw body of post requests for authentication purposes. After extensive research, I discovered that fastify does not have native support for this feature. The solutions I found online ...

The selected checkbox value does not take effect when used within an ng-if statement

Even though the ng-model value is present, it is not applied to the checkbox under ng-if. The update only occurs on double click. <div ng-show="isTrue == true"> <label> <input type="checkbox" name="test1" ng-model="a.testModel[0]" ng-true ...

Having difficulty displaying Laravel API data with Relationship in Vue Js

Working on a project that involves Laravel 10 API and Vue.js 3 frontend In my EmployeeController.php file, I have three models: Employee, Title, and Salary. The Employee model has a many-to-many relationship with the Salary and Title models, while the Sal ...

Ideas for displaying or hiding columns, organizing rows, and keeping headers fixed in a vast data table using jQuery

My data table is massive, filled with an abundance of information. Firstly, I am looking to implement show/hide columns functionality. However, as the number of columns exceeds 10-12, the performance significantly decreases. To address this issue, I have ...

"Initial loading issue with bootstrap carousel causes slides not to slide smoothly

I am currently working on implementing a slider carousel using Bootstrap. Although the 'active' image loads successfully, the controls and slide functionality are not working as expected. Initially, I believed this exercise would be straightforwa ...

Manipulating the DOM results in the SWF being reloaded

Currently, I am utilizing jQuery to insert an SWF into the DOM. However, when the SWF loads and I attempt to clone or wrap it, the SWF ends up reloading. Preventing this reload is crucial for me. Here's an example: $('#test9').before(&apo ...

An undefined PHP index error was encountered by Ajax, while the other one did not face the same issue

I encountered an issue with ajax where I am receiving an undefined index error on my variables when making a call. Strangely, I have other ajax calls functioning perfectly fine across my website except for this particular one which is giving me troubles. I ...

It appears that the pixel sizes are different than what was originally designed

In my project, I have a header panel where the burger button is designed with a width of 32px and height of 24px. .header { display: flex; font-weight: bold; font-size: 50px; height: 100px; border: 1px solid black; position: relativ ...

Unable to access the "target" property while transferring a value from child to parent component

Within my project, the student component is considered a child component of the main app component. Inside the template of the student component, there is an input element defined like so: <input type='text' #inputbox (keyup)='onkeyUp(i ...

I am seeking guidance on how to update the HTML content being viewed in the browser when a user changes the selected option within a <select> element in ASP.NET

Hello, I'm just starting to learn about web development and ASP.Net. Can anyone help me figure out how to dynamically change the HTML content displayed in the browser when the user selects a different option from a <select> element? @*DropDown: ...

NodeJS API integration failure during ReactJs login attempt

Currently, I am tackling a small project on implementing user login functionality in ReactJs with Nodejs and Express-session. The issue I am facing is that my front end (React login page) isn't functioning properly. Below is the Fetch API code snippet ...

Vue component encounters undefined error when passing prop array through component

My challenge is passing an array of dates to my component, but I keep encountering this error: [Vue warn]: Property or method "dates" is not defined on the instance but referenced during render I'm puzzled by this issue because I am receiving the ...

Change URL link after login user with javascript

Is there a way to generate a URL link based on the user's name (gmail)? For example: The code below is somewhat suitable for my needs. However, I am trying to figure out how to automatically retrieve the username and populate it in the input field. ...

Tips on customizing the appearance of two Material-UI Sliders across separate components

Looking to customize two sliders, each within their own react component. Slider in the first component const customizedThemeSlider1 = createTheme({ overrides:{ MuiSlider: { thumb:{ color: "#4442a9", marg ...