用鼠标在 canvas 上绘制矩形与鼠标坐标不同步

Drawing rectangle with mouse on canvas is not insync with mouse coordinates

我正在尝试通过鼠标拖动到 canvas 上绘制矩形。 canavs 覆盖在 html5 视频 js 播放器上。正在绘制矩形,但它并没有从正确的坐标开始下降。

我的 canvas(覆盖在视频上)的渲染周围有一些边距,例如 space(不是我检查过的边距)。我认为这是矩形与鼠标光标不同步的原因(有点偏离)。这是我的代码

 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 文件

.视频容器{

 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;
  }
}

应用截图

如果你能看到,红色 canvas 周围有像 space 这样的边距。这就是我认为我的鼠标和矩形要关闭多少。

我做了这个 codesandbox 这就是您想要实现的目标 我不得不稍微调整代码以使其工作,我认为主要原因是某些元素的默认边距或填充。通过设置

*{
   margin:0;
   padding: 0
 }

scss 文件的顶部开始正确绘制。