HTML5 Canvas distortion

后端 未结 1 1040
花落未央
花落未央 2021-01-16 20:33

I am trying to include a canvas element over a dynamically sized video that will load asynchronously. On the canvas, the user will be able to drag and resize a rectangle sel

相关标签:
1条回答
  • 2021-01-16 21:09

    Here's skeleton showing how to account for resizing and scrolling when calculating mouse position.

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var cw=canvas.width;
    var ch=canvas.height;
    function reOffset(){
      var BB=canvas.getBoundingClientRect();
      offsetX=BB.left;
      offsetY=BB.top;        
    }
    var offsetX,offsetY;
    reOffset();
    window.onscroll=function(e){ reOffset(); }
    window.onresize=function(e){ reOffset(); }
    
    var isDown=false;
    var startX,startY,mouseX,mouseY;
    
    var $mouse=$('#mouse');
    $("#canvas").mousemove(function(e){handleMouseMove(e);});
    
    function handleMouseMove(e){
      // tell the browser we're handling this event
      e.preventDefault();
      e.stopPropagation();
      // calc the current mouse position
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      // report the mouse position
      $mouse.text('Mouse position: '+mouseX+' / '+mouseY);
    }
    body{ background-color: ivory; }
    #canvas{border:1px solid red; }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <h4 id=mouse>Move the mouse around the canvas.</h4>
    <canvas id="canvas" width=300 height=300></canvas>

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