how to properly position an image using javascript

I have two tilesheet images and I have successfully rendered them, but I am struggling to figure out how to place the character in front of the map.

https://i.stack.imgur.com/n1a3Q.png

I have placed these images in two different JavaScript files.

This is the character JavaScript file:

function drawFrame(frameX, frameY, canvasX, canvasY) {
  ctx.drawImage(img,
  frameX * WIDTH, frameY * HEIGHT, WIDTH, HEIGHT,
  canvasX, canvasY, SCALED_WIDTH, SCALED_HEIGHT);
}

loadImage();

This is the map JavaScript file:

function drawMap() {
   for (var r = 0; r < rowTileCount; r++) {
      for (var c = 0; c < colTileCount; c++) {
         var tile = ground[ r ][ c ];
         var tileRow = (tile / imageNumTiles) | 0;
         var tileCol = (tile % imageNumTiles) | 0;
         ctx.drawImage(tilesetImage, (tileCol * tileSize), (tileRow * tileSize), tileSize, tileSize, (c * tileSize), (r * tileSize), tileSize, tileSize);
      }
   }window.requestAnimationFrame(drawMap);
}

Answer №1

requestAnimationFrame continuously invokes the drawMap() function, causing the map to be redrawn on top of the previous image with each animation frame.

To streamline this process, consolidate all drawing methods into a single function where you can specify the sequence in which elements are drawn. Replace the use of the current drawFrame function with requestAnimationFrame inside this new function to ensure that all items are redrawn in the desired order with each frame.

function drawEverything() {

    drawMap();
    drawFrame();

    window.requestAnimationFrame(drawEverything);
}

Initiate the animation by calling drawEverything() when you are prepared.

Additionally, if any objects will be moving within your canvas animation, remember to clear the canvas before each redraw to prevent a chaotic accumulation of colors.

function drawEverything() {

    // Clear the existing frame
    // (Note: adjust the width and height values based on your canvas dimensions)
    ctx.clearRect(0, 0, 400, 300);

    drawMap();
    drawFrame();

    window.requestAnimationFrame(drawEverything);
}

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

Having trouble with the installation of Parcel bundler via npm

Issue encountered while trying to install Parcel bundler for my React project using npm package manager. The terminal displayed a warning/error message during the command npm i parcel-bundler: npm WARN deprecated [email protected]: core-js@<3 is ...

Keeping JSP current with changes made to files on the client side

Currently, I am tackling a project that consists of two main components: a) A Java Application that runs on a client machine. b) A Web Application that is hosted on a web server. The Java Application generates results at random intervals. These results n ...

Using the tensorflow library with vite

Greetings and apologies for any inconvenience caused by my relatively trivial inquiries. I am currently navigating the introductory stages of delving into front-end development. Presently, I have initiated a hello-world vite app, which came to life throug ...

Challenges faced with dividing a string in JavaScript

Having trouble splitting a string in JavaScript, I can't seem to make it work. This is the JavaScript code I am using: var str = 'TestApplication20 Application200'; var parts = str.match(/(\d+)(\D.+)/).slice(1); var id = parts[0 ...

Guide to retrieving fresh information from an API using a desktop application built on node and electron

Looking for advice on efficiently retrieving new order data from the Shopify API for a private desktop application I'm working on. Should I query the API at regular intervals while the application is active, or is there a way to implement webhooks in ...

Ways to extract metadata from a given URL

Recently, I've delved into the world of JavaScript and I'm looking to extract metadata from a given URL. Whenever a URL is entered into an input field, I want to retrieve its meta data - a simple task in HTML using JavaScript. However, every time ...

Incorporate a JavaScript script into an Angular 9 application

I have been experiencing issues trying to add a script.js file to angular.json and use it in one component. Adding a script tag directly to my HTML file is not the ideal solution. Can someone suggest an alternative approach or point out what I may be missi ...

What is the process for loading a script file from within a component's HTML?

My goal was to include a specific script file in the component html, but I noticed that when I added the script reference within the html itself, the inner script file was not rendered along with the component on the page. Component import { Component } ...

Guide for sending token through Authorization in Laravel 8 API

I am currently utilizing Laravel 8 as an API REST and encountering an issue where my token is null when sent in the AJAX request. I have successfully handled logins and requests without tokens, but this specific scenario has me puzzled. Within my JavaScri ...

Choosing the subsequent div after the current one using Jquery

I am currently in the process of creating a drop-down menu button that, when clicked, reveals the previously hidden div underneath it. The code is functioning properly without the use of $(this).next, but it is displaying all divs with the class .menudrop ...

Add a new element to the page with a smooth fade-in animation using jQuery

var content = "<div id='blah'>Hello stuff here</div>" $("#mycontent").append(content).fadeIn(999); Unfortunately, the desired effect is not achieved with this code. I am trying to create a sleek animation when adding new content. ...

trouble with phonegap javascript ajax integration

I'm new to app development and I've been trying to create a mobile app using PhoneGap. I have a remote shared server that contains a MySQL table. My goal is to sign up a user, then send the data via JavaScript and AJAX to a PHP server page that w ...

Send form using ajax technology

I am in the process of developing a website using GitHub pages and Jekyll. One of the key features I want to include is a contact form that allows users to send emails. To implement this functionality, I have decided to use Formspree. After creating an ac ...

Is there a way for me to retrieve the variable from one function and use it in another

I have a tool for managing images with descriptions that allows me to edit both the text and the image file. The challenge is saving the modifications I make in my database. Currently, I can only save changes if I modify the image itself. If I only update ...

I'm looking for assistance on how to execute a render right after making a put or delete request

class ProductApp extends Component { constructor() { super(); this.state = { currentProduct: null, items: [], }; this.handleUpdateSubmit= this.handleUpdateSubmit.bind(this); } componentDidMount() { axios.get('h ...

Exploring the transformation of asynchronous callbacks to promises in Node.js

As a novice, I am currently in the process of developing a User Management system using NodeJS. Previously, I had implemented it with MongoDB and Express, but now I am rebuilding it with Express, Sequelize, and Postgresql to enhance my understanding of cer ...

Displaying the URL of a link on the screen using jQuery

I am looking for a solution to add a link address after the link itself in a table containing reference links for our staff. I have used CSS to achieve this in the past, but the address was not copyable by users. Instead, I am interested in using jQuery&ap ...

What is the best way to use JavaScript to conceal a section of a form div?

After receiving some code from a certain platform and implementing it to hide part of my form div element, I noticed that the element hides and unhides quickly when running in a browser. This rapid hiding and showing behavior occurs when clicking on the bu ...

Change the boxShadow and background properties of the material-ui Paper component

I am currently referencing their documentation found at this link in order to customize default Paper component properties. Below is the code snippet I have: import { styled } from '@mui/material/styles'; import { Modal, Button, TextField, Grid, ...

Crafty Checkbox Selector [ leveraging jquery ]

I have created some fake checkboxes using elements like <span> after the real checkbox and they are working fine! However, I am having trouble counting the checked checkboxes when a checkbox is clicked. I have tried using methods like: $(".elm:chec ...