我有使用canvas
绘制区域的代码。有没有办法使用Web Workers绘制它们?我知道Worker无法访问DOM,但我看到了人们使用drawImage的例子。
也许有人做这样的事情?
绘图代码:
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();
}
答案 0 :(得分:0)
您可以使用屏幕外画布
const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('bitmaprenderer');
const offscreenCanvas = new OffscreenCanvas(canvas.width, canvas.height);
const worker = new Worker('worker.js');
worker.postMessage({msg: 'init', canvas: offscreenCanvas}, [offscreenCanvas]);
并在worker.js文件中执行繁重的任务
self.onmessage = function(ev) {
if(ev.data.msg === 'init') {
canvas = ev.data.canvas;
ctx = canvas.getContext('2d');
ctx.setTransform(1, 0, 0, 1, 0, 0)
}
}