I'm working with Arduino and I'm using an Accelerometer. I want to make a 2D line based on the x and y variables from the accelerometer.
I'm trying to it with this code:
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);
});
});
So every time the accelerometer changes variables, it draws a new line. This results in a lot of lines, but I want only one which is constantly changing. I tried to do it with the if statement if ($canvas.childElementCount > 0), but this won't help.
Here is a very simple example of drawing something on a canvas with a variable.
I believe your issue is in the way you are using the
clearRectto clear the canvasRun that code snippet to see it in action.
The slider controls the Y position of a "line" that I'm drawing in the canvas, there should be just one line visible on the screen at any time.
The key is to wipe the screen:
ctx.clearRect(0, 0, canvas.width, canvas.height);before we draw anything
Looking at your code you are doing a few things inside the "accelerometer change" function that you should consider doing outside here is what I mean:
Those should not be changing as the accelerometer changes so I would keep them out
The other sticky point is your call to:
1000, $yTestyou should clear the entire canvas start at0,0drawing.width, drawing.heightare not the same ascanvas.width, canvas.heightif I change that on my example it certainly will not wipe the canvas