Click in Canvas is three pixels off

后端 未结 1 1808
我在风中等你
我在风中等你 2020-12-21 09:10

I\'ve spent the whole day trying to get a click over my canvas to return the pixel xy offset. What a mission this has been!

This is what I\'ve ended up with:

<
相关标签:
1条回答
  • 2020-12-21 10:07

    As you've discovered, border size is counted in calculating mouse position.

    So wrap your canvas in a container div with the container div having the 20px border.

    This takes away the extra calculations needed if the border were on the canvas itself.

    Note: I put the styles for #borderDiv & #myCanvas in a Style section in the Header.

    var canvas = document.getElementById('myCanvas');
    canvas.addEventListener('click', on_canvas_click, false);
    
    var context=canvas.getContext('2d');
    
    context.fillStyle='red';
    context.fillRect(0,0,10,1);
    context.fillRect(0,0,1,10);
    
    function getNumericStyleProperty(style, prop) {
      return parseInt(style.getPropertyValue(prop),10);
    }
    
    function on_canvas_click(ev) {
      var boundingRect = ev.target.getBoundingClientRect();
      var x = ev.clientX - boundingRect.left,
          y = ev.clientY - boundingRect.top;
    
      $("#logX").text("x="+x);
      $("#logY").text("y="+y);
    }
    #borderDiv{margin:0px; width:100px; height:1000px; border:20px solid black;}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <div id="logX">x</div>
    <div id="logY">y</div>
    
    <div style="margin-left:100px">
      <div style="margin-left:100px">
        <div id='borderDiv'>
          <canvas id="myCanvas" width=100 height=1000 style="cursor:crosshair"></canvas>
        </div>
      </div>
    </div>

    0 讨论(0)
提交回复
热议问题