Axis helper code :
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const AXIS_LENGTH = 50; // Length of the axis lines
function drawAxis(mouseX, mouseY) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw vertical axis line
ctx.beginPath();
ctx.moveTo(mouseX, mouseY - AXIS_LENGTH / 2);
ctx.lineTo(mouseX, mouseY + AXIS_LENGTH / 2);
ctx.stroke();
// Draw horizontal axis line
ctx.beginPath();
ctx.moveTo(mouseX - AXIS_LENGTH / 2, mouseY);
ctx.lineTo(mouseX + AXIS_LENGTH / 2, mouseY);
ctx.stroke();
}
document.addEventListener("mousemove", function (event) {
const mouseX = event.clientX;
const mouseY = event.clientY;
const invertedX = window.innerWidth - mouseX;
const invertedY = window.innerHeight - mouseY;
drawAxis(invertedX, invertedY);
});
and
main.js :
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let isDrawing = false;
let lastX = 0;
let lastY = 0;
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
function startDrawing(e) {
isDrawing = true;
[lastX, lastY] = [canvas.width - (e.pageX - canvas.offsetLeft), canvas.height - (e.pageY - canvas.offsetTop)];
}
function draw(e) {
if (!isDrawing) return;
const x = canvas.width - (e.pageX - canvas.offsetLeft);
const y = canvas.height - (e.pageY - canvas.offsetTop);
ctx.strokeStyle = 'black';
ctx.lineWidth = 5;
ctx.lineCap = 'round';
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(x, y);
ctx.stroke();
[lastX, lastY] = [x, y];
}
function stopDrawing() {
isDrawing = false;
}
canvas.addEventListener('mousedown', startDrawing);
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', stopDrawing);
canvas.addEventListener('mouseout', stopDrawing);
canvas.addEventListener('touchstart', (e) => {
e.preventDefault();
startDrawing(e.touches[0]);
});
canvas.addEventListener('touchmove', (e) => {
e.preventDefault();
draw(e.touches[0]);
});
canvas.addEventListener('touchend', stopDrawing);
function clearCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
// Listen for window resize event
window.addEventListener('resize', resizeCanvas);
I want the axis helper to be in the place of inverted mouse coordinates. so when i draw in inverted stroke the axis will work as a guide for where will the stroke appear
I tried directly type the function in my main js file but it did not work. I could see the axis but when I try to draw it becomes wider and the stroke does not appear. OR is there is any way to use 2 canvas elements at the same time with also the index of the elements to be same.