Reputation: 7267
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);
Upvotes: 0
Views: 4853
Reputation: 5520
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>
Upvotes: 4
Reputation:
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);
Upvotes: 2