Wednesday, 9 March 2022

Shift line without tearing its ends in html canvas

I am trying to create an application where the line follows y of my mouse and it's shifted to the left every x ms.

The problem is that there are artifacts on the joins of each line, like in the picture below.

How can I prevent it?

And potentially smooth the lines. The main part of the question is how to prevent tearing but if you have an idea of how to smooth this line let me know.

enter image description here

Code below or alternativly JsFiddle

let y = null

const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');

ctx.strokeStyle = 'red';
ctx.lineCap = 'round';
ctx.lineJoin = 'round'

ctx.lineWidth = 5;

const width = ctx.canvas.width
const height = ctx.canvas.height

let prevY = null;


const onMouseUpdate = (e) => {
    y = e.pageY;
}
const shift = 10

canvas.addEventListener('mousemove', onMouseUpdate, false);
canvas.addEventListener('mouseenter', onMouseUpdate, false);

function draw() {
    const rect = canvas.getBoundingClientRect()
    const yTarget = y - rect.top

    ctx.beginPath()
    ctx.moveTo(width - shift, prevY);
    ctx.lineTo(width, yTarget);
    ctx.stroke();
    prevY = yTarget

    const imageData = ctx.getImageData(shift, 0, width - shift, height);
    ctx.putImageData(imageData, 0, 0);
    ctx.clearRect(width - shift, 0, shift, height);
}
setInterval(draw, 300)



from Shift line without tearing its ends in html canvas

No comments:

Post a Comment