根据变量绘制一条 canvas 线

Drawing a canvas line based on variables

我正在使用 Arduino 并使用加速度计。我想根据来自加速度计的 xy 变量制作一条二维线。

我正在尝试使用此代码:

board.on("ready", () => {
  const accelerometer = new Accelerometer({
    controller: "MPU6050"
  });
  accelerometer.on("change", function () {
    const {
      acceleration,
      inclination,
      orientation,
      pitch,
      roll,
      x,
      y,
      z
    } = accelerometer;
      const $yPos = y * 100 * 10;
      const $canvas = document.querySelector(`.simulation__line`);
        if ($canvas.childElementCount > 0) {
          $canvas.innerHTML = ``;
        }
      const drawing = $canvas.getContext("2d");
      drawing.beginPath();
      drawing.moveTo(1000, 1000 - $yPos);
      drawing.lineTo(0,  1000);
      drawing.lineTo(-1000, 1000 + $yPos);
      drawing.stroke();
      drawing.clearRect(1000, $yTest, drawing.width, drawing.height);  
  });
});

因此每次加速度计更改变量时,它都会绘制一条新线。这导致很多行,但我只想要一个不断变化的行。我尝试使用 if 语句 if ($canvas.childElementCount > 0) 来完成它,但这无济于事。

这里是一个非常简单的例子,在 canvas 上用变量绘制一些东西。
我认为您的问题在于您使用 clearRect 清除 canvas

的方式

<input type="range" min="1" max="99" value="10" id="slider" oninput="draw()">
<br/>
<canvas id="canvas"></canvas>

<script>
  function draw() {
    y = document.getElementById("slider").value
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.fillRect(0, y, 250, 3);
  }

  // init canvas
  var canvas = document.getElementById('canvas');
  canvas.height = (canvas.width = 250)/2;
  var ctx = canvas.getContext('2d');
  draw();
</script>

运行 查看该代码片段的实际效果。
滑块控制我在 canvas 中绘制的 "line" 的 Y 位置,屏幕上任何时候都应该只有一条线可见。

关键是擦屏:
ctx.clearRect(0, 0, canvas.width, canvas.height);
在我们画任何东西之前


看看你的代码,你在 "accelerometer change" 函数内部做了一些你应该考虑在外面做的事情,我的意思是:

  const $canvas = document.querySelector(`.simulation__line`);
  const drawing = $canvas.getContext("2d"); 

那些不应该随着加速度计的变化而改变,所以我会把它们拒之门外


另一个棘手的问题是你打电话给:

  drawing.clearRect(1000, $yTest, drawing.width, drawing.height); 
  • 在你开始画任何东西之前,这应该是第一个
  • 不确定为什么要从 1000, $yTest 开始,您应该清除整个 canvas 从 0,0
  • 开始
  • drawing.width, drawing.heightcanvas.width, canvas.height 不同,如果我在我的示例中更改它肯定不会擦除 canvas