The mouse coordinates do not align with the drawing of a rectangle on the canvas

I am having some issues with drawing a rectangle on mouse drag over the canvas that is overlayed on an HTML5 video JS player. The rectangle is being drawn, but it does not align correctly with the mouse coordinates.

I suspect that the canvas, which is overlaid on the video, has some extra space around it that is causing the misalignment between the rectangle and the mouse cursor. Here is my code:

 onMouseDown = (e) => {
        this.setState({
            
        })
        let start_x = e.clientX
        let start_y = e.clientY

        this.setState({
            is_drawing: true
            draw_start_x: start_x,
            draw_start_y: start_y
        },)
    }

onMouseMove = (e) => {
        let myCanvas1 = document.getElementById('myCanvas')
        let ctx1 = myCanvas.getContext('2d')
     
        if(this.state.is_drawing){

            ctx1.clearRect(0, 0, myCanvas.width, myCanvas.height);
            ctx1.beginPath()
            let width = e.clientX - this.state.draw_start_x
            let height = e.clientY - this.state.draw_start_y
           
            ctx1.fillStyle = '#000'
            ctx.fillRect(this.state.draw_start_x, this.state.draw_start_y, width, height)
            ctx1.stroke()
        }
    }

render(){
        return (
            <div>
                <div className='video-container data-vjs-player'>
                    <canvas
                        id="myCanvas"
                        className='myCanvas'
                        onMouseDown={this.onMouseDown}
                        onMouseMove={this.onMouseMove}
                        onMouseUp={this.onMouseUp}
                        onClick={this.onClick}
                    />
                    <video
                        ref={ node => this.videoNode = node }
                        // onContextMenu="return false;"
                        //ref={this.video_element}
                        className="video video-js video-el vjs-big-play-centered vjs-default-skin"
                        id="video-el" loop={false} controls>
                        <source
                            src="https://www.rmp-streaming.com/media/big-buck-bunny-360p.mp4" type="video/mp4"/>
                    </video>
                    <button className="play-btn" onClick={this.playPause}>Play</button>
                </div>
            </div>

        )
    }

}

scss file

.video-container{

 background-color: aliceblue;
  width: 50%;
  height: calc(100% - 250px);
  position: relative;
  margin: 0;

  .myCanvas{
    position: absolute;
    top: 0;
    left: 0;
    z-index: 10;
    background-color:rgba(255,0,0,0.5);
  }
  .video {
    width: 100%;
    height: auto;
    position: absolute;
    top: 0;
    left: 0;
  }
  .play-btn{
    position: relative;
  }
}

Screenshot of the apphttps://i.stack.imgur.com/N6gr4.png

It appears that there is some additional space around the red canvas in the screenshot provided above. This extra space might be the cause of the misalignment between the mouse and the rectangle.

Answer №1

After working on it, I created a codesandbox to help you achieve the desired outcome. I had to make some adjustments to the code in order for it to function correctly. It seems that the issue may have been caused by default margins or padding on certain elements. By adding

*{
   margin:0;
   padding: 0
 }

to the beginning of the scss file, the rendering started to display properly.

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

Best practices for implementing JavaScript in JSP pages

After researching various sources, I have come across conflicting opinions on the topic which has left me feeling a bit confused. As someone new to web programming using java EE, I am looking to integrate javascript functions into my code. It appears that ...

Designing a unique customized top navigation bar in Magento 1.9.2

I recently attempted to create a unique top menu in magento 1.9.2 by modifying the Navigation.php file located at app/code/core/Mage/catalog/Block/. I added some custom classes in an effort to customize the menu. In order to achieve this customization, I ...

Is the disable feature for React buttons not functioning properly when incorporating Tailwind CSS?

import React, { useState } from "react"; import facebook from "../UI/icons/facebook.png"; import Button from "../UI/Button/Button"; import Card from "../UI/Card/Card"; import twitter f ...

Changing JSON variable letter case to lowercase using C#

Utilizing the JSONPEncoderFactory and JSONPBehavior method has allowed me to incorporate JSONP into WCF seamlessly. Everything is set up correctly and my service successfully returns data without any issues. However, I am faced with the challenge of conve ...

Toggle button to collapse the Bootstrap side bar on larger screens

I am currently utilizing the following template: An issue I am facing is that I want my sidebar to either shrink or hide when a button is clicked, specifically on a 22" PC screen. I have experimented with several solutions without achieving success. Alt ...

When PHP is connected to the database, Ajax remains inactive and does not perform any tasks

I am currently working on setting up a simple connection between JavaScript and my database using ajax and PHP. The goal is for JavaScript to receive a name from an HTML form, make changes to it, send it to PHP to check if the name already exists in the da ...

There is a slight misalignment when trying to horizontally center a character within a div

I've experimented with various methods like using a px width or em widths. I've attempted nesting a span and trying different styles such as text-align:center or margin:0 auto. I can manage to center either the R or the S, but struggling to get ...

Load grid data only when the tab is clicked in ExtJS

Our app features a dynamic grid loaded with multiple tabs, each containing one or more grids. The issue currently is that when the application loads, it automatically calls all the URLs instead of waiting for the user to click on a tab. We want to optimi ...

Why Jquery's nth-child selection and conditional formatting are failing to work

I am working with a table and need to format specific data fields based on their content. For instance, any field less than 95% should be highlighted in red. Below is the jQuery code I am using: $(function(){ $('#ConditionalTable td:nth-child(2n ...

Reduce and combine JavaScript files without the need for Grunt or Gulp

My project involves working with over 50 JavaScript files that I want to combine and compress to optimize file size and minimize HTTP requests. The catch is, the client's system does not have Node or npm installed. How can I accomplish this task witho ...

When using Tailwind, be aware that the @screen directive does not automatically generate media queries in

Angular 12 & tailwind ^3.0.12 No media queries are being generated on the screen after compilation based on breakpoints. section { @apply w-full px-6 py-24; @screen sm { @apply py-14; } @screen md { @apply px-0 py-20 max-w-5xl mx-auto; ...

How to eliminate subdomains from a string using TypeScript

I am working with a string in TypeScript that follows the format subdomain.domain.com. My goal is to extract just the domain part of the string. For example, subdomain.domain.com should become domain.com. It's important to note that the 'subdoma ...

What is the best way to execute operations on two distinct datasets within a single function using RxJS?

Is there a way to perform operations on two separate data collections within a single function in RxJS, returning an observable instead of void? This function is located within a service and I intend to subscribe to it from my component. I believe some re ...

Hiding a Div Using jQuery Depending on User's Choice

Currently, I am in the process of developing an employee directory using AJAX/jQuery with the assistance of the Random User Employee Directory API. You can access the data feed that I am utilizing by following this link: I have successfully created a webp ...

submission of form data and automatic redirection to another page

Seeking advice on managing form submissions and page redirection. I have a landing page with a basic form, where users select criteria and are then redirected to page2 displaying tabular data and query information. When submitting the form on Page1, data ...

Creating a dynamic JSON array with a single key as an array

After converting data from an excel sheet into a json array, here is the structure: [{ 'booktitle': 'Leading', 'bookid': '56353', 'bookauthor': 'Sir Alex Ferguson' }, { 'booktitle&ap ...

It is not possible to delete a class from an element once it has been added

Issue can be replicated by visiting the following URL: Click on the hamburger icon to open the navigation menu Click on "Services" Click "< Services" within the submenu to attempt to go back For some reason, the removeClass method is not removing the ...

Exploring how to incorporate Express middleware into Firebase Functions for handling HTTPS requests

Encountering a challenge while using Express middleware with Firebase Functions. In this sample, a function is linked to the app() instance as shown below: app.get('*', (req, res) => { res.send(`Hello ${req.user.name}`); }); exports.autho ...

Keeping the Bootstrap popover anchored to the content

I have a functional bootstrap popover that includes a time attribute. However, I am looking to enhance its functionality so that it remains open when the mouse is on the content and closes only when the mouse leaves the content. Here is the relevant code ...

Can the functionality of two-way data binding be achieved in Angular without utilizing ng-model and ng-bind?

During an interview, I was presented with this question which sparked my curiosity. While I have a foundational understanding of AngularJS and its ability to enable two-way data binding using ng-model and ng-bind, I am interested in exploring alternative ...