0

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);
CJAY
  • 6,989
  • 18
  • 64
  • 106
  • 4
    Possible duplicate of [How to Copy Contents of One Canvas to Another Canvas Locally](https://stackoverflow.com/questions/4405336/how-to-copy-contents-of-one-canvas-to-another-canvas-locally) – Vasile Florin Vilsan May 28 '18 at 12:47
  • Agreed re dupe, https://stackoverflow.com/questions/4405336/how-to-copy-contents-of-one-canvas-to-another-canvas-locally – sifriday Feb 14 '20 at 17:50

2 Answers2

4

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>
Baro
  • 5,300
  • 2
  • 17
  • 39
2

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