【问题标题】:How to correct stroke position when drawing on canvas with image? with typescript Angular使用图像在画布上绘图时如何更正笔画位置?用打字稿角
【发布时间】:2021-01-30 16:08:50
【问题描述】:

我在画布上添加了一张图片。我想在图像上绘图,但是在绘制线条时,它没有出现在鼠标指针上方。画布容器有一个方法来验证鼠标在画布内的正确位置并且它是正确的,但是绘制的线出现在鼠标指针的下方。怎么画笔画,鼠标指针在哪里?

公共画布(){

let x;
let y;



//we determine the location of the mouse within the canvas
$('#mycanvas').mousemove(function(e){

  var rect = e.target.getBoundingClientRect();
  x = e.clientX - rect.left; //x position within the element.
  y = e.clientY - rect.top;  //y position within the element.
  console.log("X : " + x );
  console.log("Y : " + y );
});



const canvas = <HTMLCanvasElement> document.querySelector("#mycanvas");
const ctx = canvas.getContext("2d");


//Agregamos imagen al canvas
const image = new Image();
image.src = 'assets/img/human.png';
image.onload = function(){
  ctx.drawImage(image, 0, 0, 300, 150);
}



//paint
let painting = false;


//starting position
function startPosition(e) {
  
  painting = true;
  
  draw(e);
}

//final position
function finishedPosition() {
  painting = false;
  
  ctx.beginPath();
}


function draw(e) {
  
  if(!painting) {
    return;
  }

  ctx.lineWidth = 0.5;
  ctx.lineCap = "round";


  ctx.lineTo(x, y);
  ctx.stroke();


  ctx.beginPath();
  ctx.moveTo(x, y);
}

//EventListeners
canvas.addEventListener("mousedown", startPosition);
canvas.addEventListener("mouseup", finishedPosition);
canvas.addEventListener("mousemove", draw)

}

【问题讨论】:

  • 可以发截图吗?
  • 当然可以,但是你不会看到鼠标指针在哪里

标签: javascript html jquery typescript canvas


【解决方案1】:

使用此函数并将事件参数传递给它。获取画布元素上的绝对 x,y。

function getPosition(e) {
   this.boundingRect = canvas.getBoundingClientRect(); // canvas = canvas element
   return {
     x : (e.targetTouches) ? e.targetTouches[0].pageX - this.boundingRect.x : e.offsetX,
     y : (e.targetTouches) ? e.targetTouches[0].pageY - this.boundingRect.y : e.offsetY,
   };  
}

为了优化你可以缓存this.boundingRect变量,因为getBoundingClientRect操作很耗时

【讨论】:

  • 非常感谢您的回答。在 $ ("#mycanvas"), x = (e.targetTouches) 里面添加? e.targetTouches[0].pageX - this.boundingRect.x : e.offsetX; y = (e.targetTouches) ? e.targetTouches[0].pageY - this.boundingRect.y : e.offsetY;但结果没有改变
猜你喜欢
  • 2015-02-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-16
  • 2018-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多