I tried developing a graph drawing web app using a canvas which includes animations for lines as this:
function animateLine(x1, y1, x2, y2) {
ctx.lineWidth = 5;
const nrFrames = 30;
const dy = y2 - y1;
const dx = x2 - x1;
const incx = dx / nrFrames;
const incy = dy / nrFrames;
let tmpx = x1, tmpy = y1;
ctx.strokeStyle = 'rgba(11, 158, 131, 0.4)';
for (let i = 0; i < nrFrames; i++) {
setTimeout(() => {
tmpx += incx;
tmpy += incy;
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(tmpx, tmpy);
ctx.stroke();
}, i * 16);
}
}
But also for circles as this:
class Circle {
constructor(x, y, radius, name) {
this.x = x;
this.y = y;
this.radius = radius;
this.name = name;
}
draw() {
ctx.strokeStyle = 'black';
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.stroke();
ctx.fillStyle = 'rgb(110, 255, 255)';
ctx.fill();
ctx.fillStyle = 'black';
ctx.fillText(this.name, this.x, this.y);
}
}
Given the shared context and the fact that the functions have to run asynchronously, the strokes never have the intended color.
I see that I could add strokeStyle = ‘…’ on the line exactly above every stroke made, but I don’t believe that’s the best solution since with a lot of asychronous functions you will never have a guarantee.
Put in general terms: how is the problem of different style requirements for asychronous functions that use the same context managed?
Andrei Negoita is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.