4

这是jsfiddle

我有这个作为我的源画布

HTML

 <h1>Source Canvas</h1>
 <canvas id="source" width=436 height=567></canvas>
 <h1>Destination Canvas</h1>
 <canvas id="destination" width=436 height=567></canvas>

javascript

 var sourceImage, ctx, sourceCanvas, destinationCanvas;
        //get the canvases
        sourceCanvas = document.getElementById('source');
        destinationCanvas = document.getElementById('destination');

    //draw the source image to the source canvas
    ctx = sourceCanvas.getContext('2d');

     function start() {

                ctx.drawImage(img1, 0, 0);

                ctx.globalCompositeOperation = "source-atop";

                var pattern = ctx.createPattern(img, 'repeat');
                ctx.rect(0, 0, sourceCanvas.width, sourceCanvas.height);
                ctx.fillStyle = pattern;
                ctx.fill();

                ctx.globalAlpha = .10;
                ctx.drawImage(img1, 0, 0);
                ctx.drawImage(img1, 0, 0);
                ctx.drawImage(img1, 0, 0);
                 //ctx.globalAlpha = 1;
            }
     var img1 = new Image();
     var img = new Image();
    img.onload = function () {

              img1.onload = function () {
                  start();
              }
img1.src = "https://dl.dropboxusercontent.com/u/139992952/stackoverflow/4jiSz1.png";
}
img.src = "https://dl.dropboxusercontent.com/u/139992952/stackoverflow/BooMu1.png";

我想在我的目标画布中显示源画布中的内容。

我累了

var image, destinationCtx;

//create the image
image = new Image();

//get the base64 data
image.src = sourceCanvas.toDataURL('image/png');

//get the destination context
destinationCtx = destinationCanvas.getContext('2d');

//copy the data
destinationCtx.drawImage(image, 0, 0);

//done

但没有运气。我错过了什么吗?通过 imageData 复制,通过 Base64 数据复制,通过直接绘制复制任何方法都可以完成我的工作。当我尝试

http://jsperf.com/copying-a-canvas-element 它复制但当我把我的源画布作家它不工作?我错过了什么吗?

4

2 回答 2

12

您可以直接将一个画布复制到另一个画布上。像这样...

var destinationCtx;

//get the destination context
destinationCtx = destinationCanvas.getContext('2d');

//copy the data
destinationCtx.drawImage(sourceCanvas, 0, 0);
于 2013-07-28T08:32:31.517 回答
1

您可以使用源画布中的 getImageData 和 putImageData 到目标画布。与其他方式相比,这是最快的一种。

var sourceCtx, destinationCtx, imageData;

sourceCtx = sourceCanvas.getContext('2d');
destinationCtx = destinationCanvas.getContext('2d');

imageData = sourceCtx.getImageData(0, 0, sourceCanvas.width - 1, sourceCanvas.height - 1);

destinationCtx.putImageData(imageData, 0, 0);

来源:/ https://jsperf.com/copying-a-canvas-element

于 2017-09-14T05:34:22.870 回答