JavaScript code is functioning properly on Chrome and Internet Explorer, however, it may not be working on FireFox

Despite searching through the console, I am unable to find a solution to this issue. There are two images in play here - one is supposed to appear at specific coordinates while the other should follow the mouse cursor. However, the image intended to track the cursor is not displaying, whereas the other one is visible.

Main.js

/**
* Developed using JetBrains WebStorm.
* Created by: Script47
* Date: 22/09/13
* Time: 00:54
*/

function drawAvatars() {

// Store canvas element into variable & create an Image object
var gameCanvas = document.getElementById("gameCanvas");
var userImage = new Image();

// Set the source of the images
userImage.src = ("Images/userImage.png");

// Add event listener and call redrawAvatar function
gameCanvas.addEventListener("mousemove", redrawAvatar);
}

function redrawAvatar(mouseEvent) {

var gameCanvas = document.getElementById("gameCanvas");
var userImage = new Image();
var enemyImage = new Image();
var score = 0;

userImage.src = ("Images/userImage.png");
enemyImage.src = ("Images/enemyImage.png");

// Clear canvas for a refresh, then draw image following mouse coordinates within the canvas
gameCanvas.width = 400;
gameCanvas.getContext("2d").drawImage(userImage, mouseEvent.offsetX, mouseEvent.offsetY);
gameCanvas.getContext("2d").drawImage(enemyImage, 150, 150);

// Simple collision detection to check if user image collides with enemy image
if (mouseEvent.offsetX > 130 && mouseEvent.offsetX < 175 && mouseEvent.offsetY > 130 && mouseEvent.offsetY < 175) {
    score++;
    alert("You hit the enemy!\n Your score is: " + score);
}
}

Index.html

<!DOCTYPE html>
<html>
<head>
<title>Avoid Me | Game</title>
<link rel="stylesheet" type="text/css" href="CSS/styles.css">
<script src="JS/Main.js"></script>
</head>
<body>

<br/>

<center><h3>Avoid Me!</h3>

<br/>
<br/>

<canvas id="gameCanvas" height="300" width="400" onclick="drawAvatars();">
    <p><strong>Notice:</strong> Browser does not support canvas!</p>
</canvas>
</center>

</body>
</html>

JsFiddle

Answer №1

(Based on the code from the provided link.)

Within your mouseMovement function, you are utilizing mouseEvent.offsetX and mouseEvent.offsetY to determine the player's position. However, it is worth noting that Firefox does not support these properties. As a workaround, you can obtain the canvas' position and then subtract it from the event's pageX/pageY properties for cross-browser compatibility. Utilize the canvas's getBoundingClientRect() method to ascertain its position on the page.

Below is an alternate version of the function that should function correctly in Firefox:

function mouseMovement(mouseEvent) {
    var canvasPosition = gameCanvas.getBoundingClientRect();

    userImageX = mouseEvent.pageX - canvasPosition.left;
    userImageY = mouseEvent.pageY - canvasPosition.top;
}

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

What is the best way to retrieve the value of a selected button from a v-btn-toggle?

<v-btn-toggle v-model="toggle_one"> <v-btn flat> CAD50 </v-btn> <v-btn flat> CAD100 </v-btn> <v-btn flat> CAD1000 </v-btn> <v-btn flat> CAD10000 </v-btn> ...

Showing data in a grid format on a webpage

I created a Java program that generates an array list with values such as Hi, Hello, How, Are, You, Me, They, and Them. In addition, I developed a basic controller to convert these values into JSON format and display them on localhost:8090/greeting like t ...

Mastering div manipulation with jQuery: A step-by-step guide

I have three divs with the classes "col-md-2," "col-md-8," and "col-md-2." What I want is that when a button in the "col-md-8" div is clicked, both of the other divs should be hidden and the "col-md-8" div should expand to occupy the full width of "col-md ...

Switching from JavaScript to TypeScript resulted in React context not being located in its respective file

I previously had my context and context provider set up in a file, and everything was working perfectly. However, I recently decided to convert all of my files to TypeScript, including this one. Unfortunately, I've encountered a strange issue that I c ...

What is the best way to retrieve data from a Python file and display it in HTML?

I am struggling to transfer data from my Python file to my HTML. Below is the form I am using: <div class="form-group "> <label class="col-sm-3 col-sm-3 control-label">IP Address: </label> <div class="col-sm-9"> & ...

The challenge of margin collapse

I am currently working on resolving a margin collapse issue. I am puzzled by the overlapping paragraphs and I really need to understand why this problem is happening. I suspect it may be a collapsing margin issue. Please take a look below: https://i.sta ...

Is there a way to retrieve the BrowserRouter history from outside of the BrowserRouter component?

Here is a simplified code snippet (using react-router-v5). I am trying to figure out how to access BrowserRouter's history in the logout_Handler() function, even though I am "outside" BrowserRouter. I came across this answer on How to access history ...

Sort the array based on the enum name rather than its value

Below is an example of an enumeration: export enum Foo { AA = 0, ZZ = 1, AB = 2, ER = 5 } In my case, I want to sort my Bars based on the name of the enum (AA, AB, ER, ZZ), rather than the numerical value (0, 1, 2, 5) that they represent. ...

Navigating File Paths in Node.js

My directory structure is as follows: Main > models > file1.ejs | |> routes > file2.ejs In my code, I'm trying to require file1 from file2 like this: const variable = require("../models/file1.ejs). But what if I don't want to use relative ...

Maintaining image ratio on the entire screen

I am in search of a way to create a webpage that includes the following elements from top to bottom: Full-screen width image/background-image (maintaining aspect ratio) Navigation bar (aligned at the top right of the image) Some text Another full-screen ...

Basic exam but located in a place that is not valid

Here is a test I am working on: // import {by, element, browser} from "protractor"; describe('intro', () => { beforeEach(() => { browser.get(''); }); it('should have multiple pages', () => { let buttonOn ...

Does JavaScript automatically round large numbers?

I have a simple array: myArray = [{"egn":79090114464},{"egn":92122244001},{"egn":10005870397643185154},{"egn":10000330397652279629},{"egn":10000330397652279660},] However, when I append the values from thi ...

Steps to connect two drop-down menus and establish a starting value for both

In the scope, I have a map called $scope.graphEventsAndFields. Each object inside this map is structured like so: {'event_name': ['field1', 'field2', ...]} (where the key represents an event name and the value is an array of f ...

The different types of property 'cacheLocation' do not match

I have been working on updating an old React app from JavaScript to Typescript gradually. I started by migrating the configuration file, but encountered an error when renaming it to .TS. Here is the error message: /Users/xx/yy/lulo/src/adalConfig.ts (13, ...

Tips for optimizing performance by preloading external CSS and JavaScript files from a third-party source in a ReactJS project with webpack

Is there a method similar to using ProvidePlugin for preloading jQuery that can be used to preload third-party CSS and JS files without using import in the entry JS file? The reason I am interested in preloading these files is because I encountered an err ...

Is it possible for you to pinpoint the mistake in the code below?

I've been trying to locate an error in the function but have been unable to do so. As a beginner in this area, I would appreciate your patience. <html> <head><title>print names</title> <script langua ...

Incorporating database coordinates into Marker React Leaflet: A Step-by-Step Guide

When I retrieve coordinates from the database, they are structured as "lat" and "lon" fields. In my mapping application, I have multiple markers to display. How can I combine these two fields to pass coordinates (coord.lat and coord.lon) to the Marker comp ...

Exploring AngularJS unit testing: integrating async and await with Jasmine

I'm currently facing a challenge with unit testing my Angular service using the async/await keywords in the respective (Jasmine) unit tests below. The test for the built-in Promise is functioning correctly, however, I am encountering difficulties in g ...

The pageSize in React's Material Table does not reflect dynamic updates

Currently, I am attempting to implement pagination for material table data using TablePagination. One issue I am facing is that the pageSize property, initially defined as a state variable, does not update when the selected pageSizeOptions change. Despite ...

Trying to decide between using a Javascript or HTML5 PDF Editor?

I am in need of a solution that enables users to edit PDF files directly on an ASP.NET web page. This functionality is intended for creating templates and adding blocks/form fields to existing PDFs, complete with rulers and other necessary features. Desp ...