【问题标题】:canvas- line has offset to mouse position画布线与鼠标位置有偏移
【发布时间】:2013-03-22 18:21:49
【问题描述】:

在 Firefox 中查看这个画布示例,笔画与鼠标位置有偏移?在铬它工作。我该如何解决?

这里有一个 js 小提琴: http://jsfiddle.net/wongwong/CvhMM/2/

  var canvas, context;

// Initialization sequence.
function init () {
// Find the canvas element.
canvas = document.getElementById('imageView');


// Get the 2D canvas context.
context = canvas.getContext('2d');


// Attach the mousemove event handler.
canvas.addEventListener('mousemove', ev_mousemove, false); 
}

// The mousemove event handler.
var started = false;
function ev_mousemove (ev) {
var x, y;

// Get the mouse position relative to the canvas element.
if (ev.layerX || ev.layerX == 0) { // Firefox
  x = ev.layerX;
  y = ev.layerY;
  console.log(ev.layerX);
} else if (ev.offsetX || ev.offsetX == 0) { // Opera
  x = ev.offsetX;
  y = ev.offsetY;
}

// The event handler works like a drawing pencil which tracks the mouse 
// movements. We start drawing a path made up of lines.
if (!started) {
  context.beginPath();
  context.moveTo(x, y);
  started = true;
} else {
  context.lineTo(x, y);
  context.stroke();
}
}

init();

【问题讨论】:

    标签: html canvas offset


    【解决方案1】:

    您只需要考虑画布元素的偏移量

     // Get the mouse position relative to the canvas element.
        if (ev.layerX || ev.layerX == 0) { // Firefox
         // added -this.offsetLeft, and -this.offsetTop
          x = ev.layerX - this.offsetLeft;
          y = ev.layerY - this.offsetTop;
    
          console.log(ev.layerX);
        } else if (ev.offsetX || ev.offsetX == 0) { // Opera
          x = ev.offsetX;
          y = ev.offsetY;
        }
    

    Live Demo

    【讨论】:

      猜你喜欢
      • 2012-07-24
      • 2018-10-21
      • 1970-01-01
      • 1970-01-01
      • 2014-01-20
      • 2015-02-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多