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.