将多个屏幕外画布绘制到屏幕画布上

时间:2017-06-17 19:00:05

标签: javascript canvas

当我尝试将多个屏幕外画布渲染到屏幕画布上时,我遇到了问题。我确实得到了一个屏幕外画布,但问题是之前应该有另外两个渲染。换句话说,只渲染最后一个画布。预期的结果将是红色,绿色和蓝色的三个重叠矩形(或正方形:)。这是代码:

function rectangle(color) {
    var offScreenCanvas = document.createElement('canvas');
    var offScreenCtx = offScreenCanvas.getContext('2d');

    var width = offScreenCanvas.width = 150;
    var height = offScreenCanvas.height = 150;

    switch(color) {
        case 1: 
            offScreenCtx.fillStyle='rgb(255,0,0)';
            break;
        case 2:
            offScreenCtx.fillStyle='rgb(0,255,0)';
            break;
        case 3:
            offScreenCtx.fillStyle='rgb(0,0,255)';
            break;
    }

    offScreenCtx.fillRect(0,0,width,height);

return offScreenCanvas;
}

function draw(offScreenCanvas, x , y) {
    var canvas = document.getElementById('canvas')
    var ctx = canvas.getContext('2d');

    var width = canvas.width = window.innerWidth;
    var height = canvas.height = window.innerHeight;

    ctx.drawImage(offScreenCanvas, x, y);
}

var images = [];
var color = 1;

for (var i=0; i<3; i++) {
    var img = new rectangle(color);
    images.push(img);
    color++;
}

var x = 0;
var y = 0;

for (var i = 0; i < images.length; i++) {
    draw(images[i], x, y);
    x += 100;
    y += 100;
}

我做了一些搜索,似乎我不是第一个遇到这个问题,但我无法正常工作。

1 个答案:

答案 0 :(得分:1)

设置画布heightwidth清除画布。

代码的问题在于,当您在函数draw

中设置大小时,会导致屏幕画布被清除

设置画布大小,即使该大小相同,也会导致画布上下文重置并清除画布。所有其他画布都会渲染,但在设置屏幕画布大小时会被删除。

您的draw功能

function draw(offScreenCanvas, x , y) {
    var canvas = document.getElementById('canvas')
    var ctx = canvas.getContext('2d');

    // The cause of the problem ===================================
    // Either one of the following lines will clear the canvas
    var width = canvas.width = window.innerWidth;
    var height = canvas.height = window.innerHeight;
    //=============================================================

    ctx.drawImage(offScreenCanvas, x, y);
}

要避免这种情况,只需设置一次画布大小即可。如果需要调整画布大小并保留其内容,首先需要创建画布副本,然后调整大小,然后将副本渲染回原始文件。

演示显示5个屏幕外画布呈现在一个屏幕画布上。

&#13;
&#13;
const colours = ['#f00', '#ff0', '#0f0', '#0ff', '#00f'];
const ctx = can.getContext('2d');
can.width = innerWidth - 4;  // sub 4 px for border
can.height = innerHeight - 4;

function createCanvas(color, i) {
  const canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');
  canvas.width = 150;
  canvas.height = 150;
  ctx.font = "24px arial";
  ctx.fillStyle = color;
  ctx.fillRect(0, i * 30, canvas.width, 30);
  ctx.fillStyle = "black";
  ctx.fillText("Canvas "+i,10,(i + 0.75) * 30);
  return canvas;
}
colours.forEach((c, i) => {
  ctx.drawImage(createCanvas(c, i), 0, 0);
})
&#13;
canvas {
  border: 2px solid black;
  position : absolute;
  top : 0px;
  left : 0px;
}
&#13;
<canvas id="can"></canvas>
&#13;
&#13;
&#13;