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

How can I remove the arrow from a CSS selector?

I'm looking to enhance the appearance of a select element on my webpage, so I've crafted some custom CSS: .selectWebDropDown { background-color:Transparent; background: url(../Images/ddl_Normal.png) no-repeat right #FFFFFF !important; ...

Error 404 occurs when images are not able to load when stored in a different directory

When I encounter a custom 404 Error on my website at http://ericmuir.tk and it happens in a directory other than the home one, none of the images on the page load. I faced a similar issue with loading CSS scripts, but resolved it by using style tags which ...

Is there a way to eliminate duplicate elements from 2 arrays in Angular?

Imagine I have a scenario with two arrays: arr1 = ["Tom","Harry","Patrick"] arr2 = ["Miguel","Harry","Patrick","Felipe","Mario","Tom"] Is it possible to eliminate the duplicate elements in these arrays? The desired output would be: arr2 = ["Miguel"," ...

Utilizing data from a JavaScript array and merging it with basic HTML structure

Every day, a js array source on a remote server gets updated: var io = new Array(); nsi[0] = new Array('','Frank','','Factory worker','Mercedes',374.0,26.2,76,181,'',75,'Audi',1456.5,27 ...

Is anyone else experiencing differences in the appearance of my mega menu between Safari, Firefox, and Chrome? It seems like

When viewing in Safari, the text overlaps for some reason. It works fine on Firefox and Chrome. Here's a screenshot of the issue: Safari: https://i.stack.imgur.com/hf7v2.png Firefox: https://i.stack.imgur.com/NrOOe.png Please use Safari to test th ...

The footer is being obscured by the sidebar

#contents { width: 1100px; margin-left: auto; margin-right: auto; } #sidebar { padding: 10px; position: sticky; top: 20px; left: 10px; width: 150px; border-right: 1px solid black; float: left; } #main { padding: 15px; margin-left: ...

Adding x days to a Unix timestamp can be achieved by converting the Unix timestamp

Currently, I have the following code snippet: let currentTS = Math.floor(+new Date() / 1000) This code successfully retrieves the current date in a unix timestamp. However, my goal now is to append an additional 14 days to this unix timestamp. Could some ...

Gaining entry into a JSON object

I'm currently working on a web page that utilizes API data from the Breaking Bad website. I have received this data in JSON format, but I am struggling to figure out how to access only the objects where the "author" is "Walter White." Here is the data ...

What is the best approach for extracting functions from express routes for unit testing?

I have a JavaScript controller containing some exported routes. I am interested in accessing the functions used within these routes for unit testing purposes. While many blogs suggest creating actual HTTP requests to test express routes, I consider this t ...

triangle shape filled with a gradient that transitions between two colors

I have two triangles displayed at the bottom of my page - one on the left and one on the right. The right triangle is currently transparent but I want to add a gradient effect to it. For the triangle-bottom-right, I'd like the gradient to go from rgb ...

What could be causing the submit button on this form to not be centered by this CSS?

I have been attempting to center this submit button using CSS, however, despite researching various online resources, I have not yet discovered a solution. It seems strange that such a simple task is proving to be so challenging. td.class > div { w ...

What is the significance of the source element in Vue3's audio element?

Playing mp3 files works in Vue 2, but not in Vue3. <template> <audio src="../file_example_MP3_700KB.mp3" controls ></audio> </template> In Vue3, the code needs to be modified as follows: <template> <audi ...

Is the JavaScript Base64 image data damaged or compromised?

My current task involves selecting an image through an HTML Input and then retrieving the image using Javascript to obtain its Base64/Image Data string. However, the code I have implemented is only returning a partially corrupt or invalid representation o ...

What are the best practices for incorporating an ASP variable into Javascript code?

Trying to incorporate an ASP variable into JavaScript code, but encountering difficulties. How can this be achieved? Any suggestions? <% dim strMyString strMyString = "hello there" %> <HTML> <body> <%=strMyString%> ...

Use RxJS chaining to transform an observable of `File` objects into an observable of strings encoded in base64

I have successfully written code that converts my File object to base64: let reader = new FileReader(); reader.readAsDataURL(myFile); reader.onload = () => { let resultStrOrArrayBuf = reader.result; if (!(resultStrOrArrayBuf ...

The process of embedding variables within a JSON Array function in JavaScript

As a newcomer to JavaScript, I am facing an issue while trying to create a simple program. I am attempting to store the variables 'name', 'document', and 'code' inside the JSON array called 'records'. var records = ...

Comparing and highlighting words in strings using JavaScript

Seeking assistance with comparing and styling words as shown in the image below: https://i.stack.imgur.com/Ffdml.png I attempted using JavaScript for this task but have not been successful so far. <div class="form-group"> <div class="col-md ...

Generate a scrollable element and adjust its dimensions to fit the window

Currently, my webpage features a header at the top followed by a sidebar on the left and the main content area on the right. I am looking for a solution that will allow the main content area to scroll independently from the side bar. --------------------- ...

Retrieving CSV information from several files within a JavaScript directory

Currently, I am attempting to retrieve data from numerous CSV files using 'csvtojson'. Firstly, I gathered an array of file names in a specific directory. Then, I used a forEach loop to extract data from various CSV files and convert it to JSON ...

I'm struggling to incorporate the JQuery slideDown function into my code. Can someone lend a hand?

Why isn't the video div sliding down and displaying properly in the beginning? Any ideas on how to fix it? Here is the snippet of HTML code and JavaScript: <!DOCTYPE HTML> <html> <head> <title>Team Songs</title> <link ...