最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to copy content of one canvas to another canvas - Stack Overflow

programmeradmin1浏览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);

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);
Share Improve this question asked May 28, 2018 at 12:44 CeejayCeejay 7,30519 gold badges66 silver badges109 bronze badges 2
  • 4 Possible duplicate of How to Copy Contents of One Canvas to Another Canvas Locally – Vasile Florin Vilsan Commented May 28, 2018 at 12:47
  • Agreed re dupe, stackoverflow./questions/4405336/… – sifriday Commented Feb 14, 2020 at 17:50
Add a ment  | 

2 Answers 2

Reset to default 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/portal/wikipedia/assets/img/Wikipedia-logo-v2.png';
canvas {
  position:relative;
  width:48%;
  height:auto;
  float:left;
}
<canvas id="imgCanvas"></canvas>

<canvas id="imgCanvas2"></canvas>

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);
发布评论

评论列表(0)

  1. 暂无评论