Answer the question
In order to leave comments, you need to log in
How to draw area in Canvas using Web Workers?
I have a component that draws a graph using canvas. Due to the large number of graphs, I would like to try to make all the calculations in Web Worker. As far as I know, DOM cannot be manipulated from another thread, but I found examples of how to do this with img via drawImage. Maybe someone has experience of this kind?
The code is simple:
private draw() {
if (!this._data.length || !this.canvas) {
return;
}
let maxX = this.getMaxX(),
minX = this.getMinX(),
maxY = this.getMaxY(),
width = this.canvas.width,
height = this.canvas.height,
ctx = this.canvas.getContext("2d"),
ratioY = height / maxY;
ctx.save();
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, width, height);
ctx.restore();
ctx.beginPath();
ctx.fillStyle = this.colorMap.get(this.status);
ctx.strokeStyle = this.colorMap.get(this.status);
ctx.moveTo(width * ((maxX - +this._data[0].time) / (maxX - minX)), height);
for (let i = 0; i < this._data.length; i++) {
let d = this._data[i];
let x = width * ((maxX - +d.time) / (maxX - minX));
let y = height - (d.value * ratioY);
ctx.lineTo(x, y);
}
ctx.lineTo(width * ((maxX - +this._data[this._data.length - 1].time) / (maxX - minX)), height);
ctx.lineTo(width * ((maxX - +this._data[0].time) / (maxX - minX)), height);
ctx.fill();
ctx.closePath();
ctx.stroke();
}
Answer the question
In order to leave comments, you need to log in
I would first work on the calculations, and then try to fix everything with the "magic wand" WebWorkers
I think that here we need to remove all calculations from rendering, for example, the lineTo cycle can be calculated separately and made from this path2D and already drawn https://developer .mozilla.org/en-US/docs/Web/API/P...
After that, the transformation will immediately go away as unnecessary, especially save() - restore() is a rather expensive operation if you want speed
Well, it was not superfluous to carefully think about what unites the graphs and not to do three times what can be counted once
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question