【问题标题】:JavaScript - Wrong mouse position when drawing on canvasJavaScript - 在画布上绘图时鼠标位置错误
【发布时间】:2017-10-06 18:41:55
【问题描述】:

这里有一个问题:

https://jsfiddle.net/y5cu0pxf/

我已经搜索并尝试了很多,但找不到问题。我只是想让笔准确地绘制鼠标点击的位置,但由于某种原因它会偏移。

有什么想法吗?

代码如下:

var imageLoader = document.getElementById('imageLoader');
imageLoader.addEventListener('change', handleImage, false);

var canvas = document.getElementById('imageCanvas');
var ctx = canvas.getContext('2d');

function handleImage(e){

  var reader = new FileReader();

  reader.onload = function(event){

    var img = new Image();

    img.onload = function(){

      canvas.width = window.innerWidth * 0.5;
      canvas.height = window.innerHeight;

      var hRatio = canvas.width / img.width;
      var vRatio =  canvas.height / img.height;
      var ratio = Math.min (hRatio, vRatio);
      var centerShift_x = (canvas.width - (img.width * ratio)) / 2;
      var centerShift_y = (canvas.height - (img.height * ratio)) / 2;
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(img, 0, 0, img.width, img.height,
                    centerShift_x, centerShift_y, img.width * ratio, img.height * ratio);
    }

    img.src = event.target.result;
  }
  reader.readAsDataURL(e.target.files[0]);
}

var isDrawing;
var rect = canvas.getBoundingClientRect();
var offsetX = rect.left;
var offsetY = rect.top;

canvas.onmousedown = function(e) {
  isDrawing = true;
  ctx.moveTo(e.clientX - offsetX, e.clientY - offsetY);
};
canvas.onmousemove = function(e) {
  if (isDrawing) {
    ctx.lineTo(e.clientX - offsetX, e.clientY - offsetY);
    ctx.stroke();
  }
};
canvas.onmouseup = function() {
  isDrawing = false;
};

【问题讨论】:

  • 你知道它被抵消了多少吗?
  • 事件对象不是给出相对于元素的位置,而不是相对于页面的位置吗? - offsetX 位是否必要?尝试摆脱它。

标签: javascript css html html5-canvas


【解决方案1】:

画布和鼠标

画布和大小

画布有两个尺寸属性,一个以像素为单位表示分辨率,另一个以 CSS 单位指定显示尺寸。两者相互独立。

// HTML <canvas id = "myCan"><canvas>
// To set the resolution use the canvas width and height properties
myCan.width = 1024;
myCan.height = 1024;
// To set the display size use the style width and height
myCan.style.width = "100%"; // Note you must post fix the unit type %,px,em
myCan.style.height = "100%";

默认情况下,画布分辨率设置为 300 x 150 像素。画布显示大小将取决于布局和 CSS 规则。

当渲染到画布 2D 上下文时,您使用像素坐标而不是样式坐标进行渲染。

获取画布的位置

var canvasBounds = myCan.getBoundingClientRect();

鼠标

鼠标坐标以像素为单位。

使用一个事件处理程序来处理所有鼠标 IO

const mouse = {
    x: 0, y: 0,                        // coordinates
    lastX: 0, lastY: 0,                // last frames mouse position 
    b1: false, b2: false, b3: false,   // buttons
    buttonNames: ["b1", "b2", "b3"],   // named buttons
}
function mouseEvent(event) {
    var bounds = myCan.getBoundingClientRect();
    // get the mouse coordinates, subtract the canvas top left and any scrolling
    mouse.x = event.pageX - bounds.left - scrollX;
    mouse.y = event.pageY - bounds.top - scrollY;

要获得正确的画布坐标,您需要缩放鼠标坐标以匹配画布分辨率坐标。

// first normalize the mouse coordinates from 0 to 1 (0,0) top left
// off canvas and (1,1) bottom right by dividing by the bounds width and height
mouse.x /= bounds.width; 
mouse.y /= bounds.height; 

// then scale to canvas coordinates by multiplying the normalized coords with the canvas resolution

mouse.x *= myCan.width;
mouse.y *= myCan.height;

然后获取您感兴趣的其他信息。

    if (event.type === "mousedown") {
         mouse[mouse.buttonNames[event.which - 1]] = true;  // set the button as down
    } else if (event.type === "mouseup") {
         mouse[mouse.buttonNames[event.which - 1]] = false; // set the button up
    }
}

在拖动时捕获鼠标(按下按钮)

当为使用画布的绘图应用程序处理鼠标时,您不能直接将事件侦听器添加到画布。如果你这样做,当用户离开画布时你会失去鼠标。如果用户离开画布时释放鼠标,您将不知道按钮已打开。结果是按钮被卡住了。 (就像你的小提琴一样)

要捕获鼠标,以便获取按钮按下时发生的所有事件、用户移动画布、离开页面或离开屏幕的事件,您需要收听document' s 鼠标事件。

所以要添加上面的鼠标事件监听器

document.addEventListener("mousemove", mouseEvent);
document.addEventListener("mousedown", mouseEvent);
document.addEventListener("mouseup",   mouseEvent);

现在mouseEvent 处理所有页面点击并在按钮按下时将鼠标专门捕获到您的页面。

您可以通过检查 event.target 来检查画布上是否启动了鼠标事件

// only start mouse down events if the users started on the canvas
if (event.type === "mousedown" && event.target.id === "myCan") {
     mouse[mouse.buttonNames[event.which - 1]] = true; 
}

事件不应呈现

鼠标事件可以非常迅速地触发,某些设置以每秒 600 多个事件触发鼠标移动。如果您使用鼠标事件渲染到画布上,您将浪费大量 CPU 时间,并且您还将在 DOM 同步合成和布局引擎之外进行渲染。

通过requestAnimationFrame 使用动画循环进行绘制。

function mainLoop(time) {
   if (mouse.b1) {  // is button 1 down?
       ctx.beginPath();
       ctx.moveTo(mouse.lastX,mouse.lastY);
       ctx.lineTo(mouse.x,mouse.y);
       ctx.stroke();
   }


   // save the last known mouse coordinate here not in the mouse event
   mouse.lastX = mouse.x;
   mouse.lastY = mouse.y;
   requestAnimationFrame(mainLoop); // get next frame
}
// start the app
requestAnimationFrame(mainLoop);

这应该可以让您的绘图应用按您的意愿工作。

【讨论】:

    【解决方案2】:

    您正在使用 CSS 为画布设置静态宽度。这很好,但是它会拉伸画布以适应。您需要先找到 x 和 y 值的结果值,然后再将它们绘制到屏幕上。

    这个例子的代码变成:

    var imageLoader = document.getElementById('imageLoader');
    imageLoader.addEventListener('change', handleImage, false);
    
    var canvas = document.getElementById('imageCanvas');
    var ctx = canvas.getContext('2d');
    
    function handleImage(e) {
    
      var reader = new FileReader();
    
      reader.onload = function(event) {
    
        var img = new Image();
    
        img.onload = function() {
    
          canvas.width = window.innerWidth * 0.5;
          canvas.height = window.innerHeight;
    
          var hRatio = canvas.width / img.width;
          var vRatio = canvas.height / img.height;
          var ratio = Math.min(hRatio, vRatio);
          var centerShift_x = (canvas.width - (img.width * ratio)) / 2;
          var centerShift_y = (canvas.height - (img.height * ratio)) / 2;
          ctx.clearRect(0, 0, canvas.width, canvas.height);
          ctx.drawImage(img, 0, 0, img.width, img.height,
            centerShift_x, centerShift_y, img.width * ratio, img.height * ratio);
        }
    
        img.src = event.target.result;
      }
      reader.readAsDataURL(e.target.files[0]);
    }
    
    var isDrawing;
    var rect = canvas.getBoundingClientRect();
    var offsetX = rect.left;
    var offsetY = rect.top;
    
    var temp = document.getElementById('imageCanvas');
    
    canvas.onmousedown = function(e) {
      isDrawing = true;
    
      ctx.moveTo((e.clientX - offsetX)/(800/temp.width), (e.clientY - offsetY)/(400/temp.height));
    };
    canvas.onmousemove = function(e) {
      if (isDrawing) {
    
        ctx.lineTo((e.clientX - offsetX)/(800/temp.width), (e.clientY - offsetY)/(400/temp.height));
        ctx.stroke();
      }
    };
    canvas.onmouseup = function() {
      isDrawing = false;
    };
    window.addEventListener("scroll",function(){
     rect = canvas.getBoundingClientRect();
     offsetX = rect.left;
     offsetY = rect.top;
    })
    

    其中 800 和 400 是计算得出的画布宽度和高度,您可以使用 jQuery 轻松获取。

    我相信我已经在这里编辑了小提琴:https://jsfiddle.net/y5cu0pxf/4/

    【讨论】:

    • 如果您移动屏幕,您需要更新偏移量。我已经更新了我的答案以包含这个
    猜你喜欢
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多