css 为什么我只能画在我的画布的中心,并没有真正按照我的光标绘制

jm81lzqq  于 2023-01-14  发布在  其他
关注(0)|答案(1)|浏览(87)

canvasContent是画布本身

canvasContent.width = window.innerWidth; //probleme HERE !!!
canvasContent.height = window.innerHeight; // and HERE

let drawing = false;
let lastX;
let lastY;

// Start drawing
canvasContent.onmousedown = function(event) {
  drawing = true;
  lastX = event.clientX;
  lastY = event.clientY;
};

// Keep drawing
canvasContent.onmousemove = function(event) {
  if (drawing) {
    let x = event.clientX;
    let y = event.clientY;
    console.log(x, y, lastX, lastY);
    canvasContext.beginPath();
    canvasContext.moveTo(lastX, lastY);
    canvasContext.lineTo(x, y);
    canvasContext.stroke();
    lastX = x;
    lastY = y;
  }
};`

// Stop drawing
canvasContent.onmouseup = function() {
  drawing = false;
};

我创建了一个画布,但我只能在中心绘制。而且我的光标没有很好地放置。enter image description here
我尝试更改所有容器,例如使用绝对值或vw vh,在js中,我尝试使用偏移量代替clientX enter image description here

ikfrs5lh

ikfrs5lh1#

我不太明白你说的只能画在画布的中间是什么意思,所以我试着回答你关于它没有正确排列的评论。
对于HTML中的canvas,您可以获取边界矩形,并从clientX和Y中减去它以“归一化”坐标。
您需要执行此操作以使坐标与光标尖端对齐,因为canvas元素的viewport与其内容有偏移。
当你在画布元素上使用鼠标输入时,你几乎总是要这样做,所以我不知道为什么它没有内置它,但是你可以在这里阅读更多关于它的信息。
https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
我在下面加入了一个片段,我相信你想做什么。

const canvasContent = document.getElementById("drawing");
const canvasContext = canvasContent.getContext("2d");

// this get's the coordinates of the top left corner of the canvas
let rekt = canvasContent.getBoundingClientRect();

let lastX = 0;
let lastY = 0;
let drawing = false;

canvasContent.addEventListener("mousemove", function(event) {
  if (drawing) {

    const fixedX = event.clientX - rekt.x;
    const fixedY = event.clientY - rekt.y;

    canvasContext.beginPath();
    canvasContext.moveTo(lastX, lastY);
    canvasContext.lineTo(fixedX, fixedY);
    canvasContext.stroke();
    
    lastX = fixedX;
    lastY = fixedY;

  }
});

canvasContent.addEventListener("mousedown", function(event) {
  lastX = event.clientX - rekt.x;
  lastY = event.clientY - rekt.y;
  drawing = true;
});

canvasContent.addEventListener("mouseup", function(event) {
  drawing = false;
});
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <canvas id="drawing" style="border: 1px solid black;">
</body>
</html>

相关问题