简体   繁体   中英

How to copy content of one canvas to another canvas

I am trying to copy the content of one canvas to the other canvas which is empty, but when the code executes i am getting the following error.

framework2-debug.js:1876 TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided value is not of type '(CSSImageValue or HTMLImageElement or SVGImageElement or HTMLVideoElement or HTMLCanvasElement or ImageBitmap or OffscreenCanvas)'

i am not able to get what is wrong in my code, Can anyone help me out in this?

                var c = $("#imgCanvas");
                var ctx = c[0].getContext("2d");
                var img = $(this).find('canvas');
                ctx.drawImage(img, 10, 10);

You made mistake. ctx.drawImage doesn't accept jQuery element as parameter.

var img = $(this).find('canvas').get(0);

or

var img = this.querySelector('canvas');

or you can use getImageData and putImageData methods of canvas context:

var imgData = oldCanvas.getContext('2d').getImageData(0, 0, 100, 100);
newCanvas.getContext('2d').putImageData(imgData, 0, 0);

The trick is: draw the fist canvas element as an image on the second canvas.

 var img = new Image(); var c = document.getElementById('imgCanvas').getContext('2d'); var c2 = document.getElementById('imgCanvas2').getContext('2d'); img.onload = function() { c.drawImage(img, 0, 0); // HERE THE TRICK, Draw element as Image c2.drawImage(document.getElementById('imgCanvas'), 0, 0); } img.src = 'https://www.wikipedia.org/portal/wikipedia.org/assets/img/Wikipedia-logo-v2.png'; 
 canvas { position:relative; width:48%; height:auto; float:left; } 
 <canvas id="imgCanvas"></canvas> <canvas id="imgCanvas2"></canvas> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM