【问题标题】:Drawing area in canvas using Web Workers使用 Web Workers 在画布中绘制区域
【发布时间】:2016-12-09 07:59:35
【问题描述】:

我有使用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();
    }

【问题讨论】:

标签: javascript html5-canvas web-worker


【解决方案1】:

您可以使用离屏画布

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)
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 2016-10-08
    • 1970-01-01
    相关资源
    最近更新 更多