代码之家  ›  专栏  ›  技术社区  ›  wendykr

JavaScript画布和鼠标位置

  •  0
  • wendykr  · 技术社区  · 7 年前

    我正试图用JavaScript在HTML5中制作一个绘图板,但是工具(如铅笔、画笔等…)位置和我想象的不同。

    我发现它是不同的,因为位图(?)所以我正试图从其他人已经问过的答案中解决这个问题,但我失败了。。

    如何找到鼠标的正确位置?

    images

    这是我的HTML代码(我使用bootstrap)

    <div class="col-sm-10">
        <canvas id="c" width="900" height="500"></canvas>
    </div> 
    

    这是js(铅笔代码不是我的,我在网上找到的)

    var el = document.getElementById('c'); //캔버스
    var ctx = el.getContext('2d');  //붓
    
    function pencil () {
        var pos = getMousePos(el, e);
    
        el.onmousedown = function() {
          isDrawing = true;
          ctx.moveTo(pos.X, pos.Y);
        };
    
        el.onmousemove = function() {
          if (isDrawing) {
            ctx.lineTo(pos.X, pos.Y);
            ctx.stroke();
          }
        };
    
        el.onmouseup = function() {
          isDrawing = false;
        };
    }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Jonathan Rys    7 年前

    我找到了getMousePos函数 here 而且它看起来和你正在做的事情一样有效。但是,它接受了一个论点 e (事件)不会定义您在何处使用它。尝试将呼叫移动到 getMousePos 在定义事件的事件处理程序中。

    而且 isDrawing 未定义。

    var el = document.getElementById('c');
    var ctx = el.getContext('2d');  //붓
    ctx.strokeStyle = "#FF0000";
    
    function pencil () {
      var isDrawing = false;
    
      el.onmousedown = function(e) {
        var pos = getMousePos(el, e);
        isDrawing = true;
        ctx.moveTo(pos.x, pos.y);
      };
    
      el.onmousemove = function(e) {
        var pos = getMousePos(el, e);
        if (isDrawing) {
          ctx.lineTo(pos.x, pos.y);
          ctx.stroke();
        }
      };
    
      el.onmouseup = function() {
        isDrawing = false;
      };
    }
    
    function getMousePos(canvas, evt) {
      var rect = canvas.getBoundingClientRect();
      return {
        x: evt.clientX - rect.left,
        y: evt.clientY - rect.top
      };
    }
    
    pencil()
    <div class="col-sm-10">
        <canvas id="c" width="900" height="500"></canvas>
    </div>