首页 > 解决方案 > JavaScript 画布和鼠标位置

问题描述

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

我发现它是不同的,因为位图(?)所以我试图从人们已经问过的其他答案中修复它,但我失败了..

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

图片

这是我的 HTML 代码(我使用引导程序)

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

标签: javascripthtmlcanvaspositionmouse

解决方案


我在这里找到了 getMousePos 函数,它看起来像你正在做的事情。但是,它接受一个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> 


推荐阅读