将画布复制到另一个画布

时间:2014-09-28 10:30:13

标签: javascript jquery html5 canvas

我使用此功能将旧画布复制到新画布

function cloneCanvas(oldCanvas) {

        //create a new canvas
        var newCanvas = document.createElement('canvas');
        var context = newCanvas.getContext('2d');

        //set dimensions
        newCanvas.width = oldCanvas.width;
        newCanvas.height = oldCanvas.height;

        //apply the old canvas to the new one
        context.drawImage(oldCanvas, 0, 0);

        //return the new canvas
        return newCanvas;
    }

我使用这个功能

            var oldCanvas = $(this).parent().parent().find('td:first-child canvas')

            $("div.previewImg").append(cloneCanvas(oldCanvas))

但是我收到了这个错误:(

Failed to execute 'drawImage' on 'CanvasRenderingContext2D': No function was found that matched the signature provided

请帮助我,我怎么能解决这个错误

谢谢

2 个答案:

答案 0 :(得分:2)

首先要确保你得到一个元素而不是数组:

$(this).parent().parent().find('td:first-child canvas').first();

第二:

要从数组中复制图像数据,请使用toDataUrl()

canvasDataImg = oldCanvasContext.toDataURL("image/png");

然后画到新画布。

答案 1 :(得分:0)

var oldCanvas = $(this).parent().parent().find('td:first-child canvas')[0];
if(oldCanvas){ //Check if the element is present
    $("div.previewImg").append(cloneCanvas(oldCanvas))
}