-1
I have this code that makes me able to draw lines on the canvas: https://jsfiddle.net/475yesLw/
const canvas = document.createElement("canvas");
canvas.setAttribute("id", "canvas");
canvas.setAttribute("class", "canvas");
const context = canvas.getContext("2d");
canvas.width = 400;
canvas.height = 400;
context.lineWidth = 4;
context.strokeStyle = "red";
const brush = {
active: false,
move: false,
pos: { x: 0, y: 0 },
posPrev: null,
};
const drawLine = (line) => {
context.beginPath();
context.moveTo(line.posPrev.x, line.posPrev.y);
context.lineTo(line.pos.x, line.pos.y);
context.stroke();
};
canvas.onmousedown = () => {
brush.active = true;
};
canvas.onmouseup = () => {
brush.active = false;
};
canvas.onmousemove = (event) => {
brush.pos.x = event.clientX;
brush.pos.y = event.clientY;
brush.move = true;
};
const loop = () => {
if (brush.active && brush.move && brush.posPrev) {
drawLine({ pos: brush.pos, posPrev: brush.posPrev });
brush.move = false;
}
brush.posPrev = { x: brush.pos.x, y: brush.pos.y };
setTimeout(loop, 10);
};
loop();
document.body.appendChild(canvas);
Only if I change the position of the canvas to the center of the canvas, it no longer draws: https://jsfiddle.net/475yesLw/3/
I want no matter the position I place the canvas, make the lines based on the size of the canvas I set.