JavaScript画布和鼠标位置

时间:2018-05-17 13:14:06

标签: javascript html5 canvas position mouse

我正在尝试使用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 个答案:

答案 0 :(得分:0)

我找到了getMousePos函数here,看起来它可以与你正在做的事情一起工作。但是,它接受一个参数e(一个事件),它不会被定义在你使用它的地方。尝试将调用移动到定义事件的事件处理程序内的getMousePos

此外,isDrawing尚未定义。

&#13;
&#13;
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()
&#13;
<div class="col-sm-10">
    <canvas id="c" width="900" height="500"></canvas>
</div> 
&#13;
&#13;
&#13;