Error in the code causing images to shift positions

My JavaScript code is encountering a strange glitch, and I'm not sure if it's related to my math calculations or the way my code is structured.

The concept behind my project involves left-clicking and dragging to scroll through a map displayed on a canvas. Everything works perfectly, except for one issue - when I try to scroll a second time after releasing the mouse, the map resets back to its original x0y0 offset.

This means that I can't continue scrolling because every time I mousedown again, the map jumps back to the starting position.

Here's how I've implemented it:

//this script is part of the init function triggered on body load
canvas.addEventListener("mousedown", detectMousePosition, false);

//relevant functions
    function detectMousePosition(e){
            mouseX = e.pageX;
            mouseY = e.pageY;               
            canvas.addEventListener("mousemove", trackMovement, false);
    }

    function trackMovement(e){
    canvas.addEventListener('mouseup',onMouseRelease,false);
    offsetX = e.pageX - mouseX; //pixels to move the map along x-axis
    offsetY =  e.pageY - mouseY; //pixels to move the map along y-axis
    }

    function onMouseRelease(){
     // once the mouse is released, stop moving the map
    canvas.removeEventListener('mousemove',trackMovement,false);
    }

Any suggestions on how to resolve this issue?

Answer №1

  1. Ensure proper usage of offset_x and offset_y within the code snippet provided. Remember to add these values to the map's total offset on mouseup and reset them to zero.
  2. Avoid adding multiple mouseup handlers whenever the mouse is moved. Opt for installing the mouseup handler just once within the mousePos() function.

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 axios and jQuery for posting data

Exploring two different Vue methods: one utilizing axios and the other using jQuery: axios.post('./test.cshtml', { para: 'test_Axios', action: 'test' }) $.post('./test.cshtml', { para: 'test_JQ', action: ...

Learn how to properly configure the React useState hook within the useEffect function and in combination with the

I am currently encountering an issue with my code. At the initial page load, the program checks for an available agent and sets the setDefault state variable to true if an agent is available. Then, if a language change event occurs and there is an availabl ...

The Vue.js transition feature seems to be malfunctioning when trying to display a modal

I can't figure out why my animation isn't working with Vue transitions. Here is the code I have: <template> <teleport to="body"> <div class="modal-overlay" v-if="loading"> <transitio ...

Extensive Ajax requests are hindering brief Ajax status updates

I am currently running an ASP.NET MVC application on IIS with two main handlers, /DoWork (which takes about 10 minutes to complete) and /ReportStatus (which takes less than a second). The purpose of DoWork is to perform a task while ReportStatus provides u ...

What is the best way to initiate an animation once the one before it has finished?

I am facing an issue with my animation function where all animations play simultaneously. This is not the desired behavior; I would like to play each animation after the previous one ends. Can someone guide me on how to achieve this? canvas = document.get ...

Exploring the power of Typescript alongside Styled Components and Material UI

Working with Typescript in conjunction with MUI and Styled-Components may lead to the need to pass props directly to MUI elements to address type errors... const Index = () => { return ( <StyledButton variant="contained" > ...

I want to create a Bootstrap 4 card deck that includes expand/collapse functionality for its content. The expanded content should only impact the current

I am experiencing an issue with my card decks and expand/collapse functionality. Currently, when I expand one card in the deck, all the other cards in the row also expand, leaving a large blank area. This becomes problematic especially when the content is ...

A new WordPress plugin that includes a custom designed stylesheet featuring a hidden display property within a specific

After reloading the page, my plugin displays a constructed stylesheet. However, when I access it for the first time or reload with ctrl + f5, the constructed stylesheet does not appear. I have meticulously searched through all of the plugin code looking f ...

Unable to set default selected option with object model in ng-options [AngularJS 1.5]

Everything is loading correctly with the code below, but the default option is not being selected. In addition, one of the dropdown items has a value for option.groupJID that matches with MyCtrl.groupJID = [email protected]</a> <select id=" ...

Show information and organize tabs based on a localStorage variable

Recently, I came across a theme that intrigued me: . My goal is to utilize local storage in order to maintain the active tab even when the page is refreshed. However, I've encountered an issue where the site continues to display previous content and t ...

Execute function asynchronously after useEffect has completed

I'm curious about how to run a function following the use of useEffect to fetch data, where the function manipulates the retrieved data. import React, { useState, useEffect } from 'react'; const Result = (props) => { const [ playerN ...

Dynamic HTML element

I created an input number field and I want to dynamically display the value of this field in a container without having to refresh the page. I am currently using ajax for this purpose, but unfortunately, I still need to reload the page. HTML: < ...

Exploring the data types of dictionary elements in TypeScript

I have a model structured like this: class Model { from: number; values: { [id: string]: number }; originalValues: { [id: string]: number }; } After that, I initialize an array of models: I am trying to compare the values with the o ...

There was an unexpected error: The module "@angular-devkit/build-angular" could not be located

After entering the terminal commands ng server or ng serve, I encountered the following problem: An unexpected error occured: Module "@angular-devkit/build-angular" could not be located ...

Is it possible to retrieve any user data by id using Vue 3 Firebase Auth?

I'm a newcomer to vue/firebase and I've been able to easily access the "current user" data from authentication. However, I am struggling to write a JavaScript composable that can retrieve the user object or at least displayName when passing in an ...

Exploring methods to send a JSON object through an Express response using Node.js

Is it possible to send a JSON object via express response using res.send? Currently, I am logging the data in the console using console.log(JSON.stringify(row)), but I would like to utilize res.send to display the data on my webpage. Here are the logs: ...

The ajaxStop() function fails to trigger

My code was giving me trouble, here's what I had: $(document).ajaxStop(function() { $(this).unbind("ajaxStop"); //avoid running again after other calls finish // Show everything display(); }); And this is my Ajax function: function get ...

Using Router.back in Next.js triggers a complete page refresh

I am working on a page called pages/conversations/[id].tsx, and here is the code: import Router, { useRouter } from 'next/router' export default function ConversationPage() { const router = useRouter() ... return ( <View ...

How can I fix the NextJs error that says: "The title element should only have one child element, not an array with multiple elements"?

An issue is arising when attempting to create a component that wraps every page and expects children and a title for each page. The error message states: "Title element received an array with more than 1 element as children." import Head from "next/ ...

Conceal the element at all times

I'm facing a challenge with a paragraph element that is dynamically filled with content using Javascript. I need to hide the element whenever it doesn't have any text within it. However, I want to avoid using setTimeout or setInterval for this ta ...