user5685187
user5685187

Reputation:

React, Want to get current mouse position of the current element

I want to get the current mouse position within a <div>, and then draw something on that position in the <div>.

<chrome screen>
----------------------------------------------
|                                            |
|    <div>                                   |
|    --------------------------              |
|    |                        |              |
|    |                        |              |
|    | .  <-- mouse position and i want to draw something here  
|    |        when clicking here             |
|    |------------------------|              |
|                                            |
|--------------------------------------------|

I tried to code with React Framework. And the problem is that I cannot get an accurate position to draw something.

I googled on how to get current position of the current element in react, and tried below

render(){
    return (
        <canvas ref="canvas" className="DrawReflect" onMouseDown={this.startDrawing}>
        </canvas>
    );
}

startDrawing(e){

    switch(this.context.drawingTool){

        case "pen":
            // Stuck on getting mouse position. None of google's source is not accurate.
            //this.drawPen(e.nativeEvent.offsetX, e.nativeEvent.offsetY);
            //this.drawPen(e.pageX - e.target.offsetLeft, e.pageY - e.target.offsetTop);

            break;
    }
}

drawPen(cursorX, cursorY){
    // Just for showing drawing information in a label
    this.context.updateDrawInfo({
        cursorX: cursorX,
        cursorY: cursorY,
        drawingNow: true
    });

    // Draw something
    const canvas = this.refs.canvas;
    const canvasContext = canvas.getContext("2d");
    canvasContext.beginPath();
    canvasContext.arc(
                    cursorX, cursorY /* start position */, 
                    1, /* radius */
                    0, /* start angle */
                    2 * Math.PI /* end angle */);
    canvasContext.stroke();

}

So simply put, How do I get the current mouse position of the div in React?

Upvotes: 1

Views: 5541

Answers (1)

Anthony Z
Anthony Z

Reputation: 394

I made you a pen using e.clientX - e.target.offsetLeft and e.clientY - e.target.offsetTop. The top left corner of the canvas (in pink) is giving me 0,0 which seems right.

Upvotes: 2

Related Questions