如何将一个画布的内容复制到另一个画布

时间:2018-05-28 12:44:48

标签: javascript canvas html5-canvas

我正在尝试将一个画布的内容复制到另一个空白的画布,但是当代码执行时,我收到以下错误。

print('I have worked {} days'.format(workdays['work'].count(',')+1))

我的代码无法解决问题,任何人都可以帮我解决这个问题吗?

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

2 个答案:

答案 0 :(得分:1)

你犯了错误。 ctx.drawImage 不接受jQuery元素作为参数。

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

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

或者你可以使用画布上下文的 getImageData putImageData 方法:

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

答案 1 :(得分:1)

诀窍是:在第二个画布上绘制第一个canvas元素作为图像。



<div class="container">
    <div class="row d-flex">
        <div class="col-sm-3 bg-success">col-sm-3</div>
        <div class="col-auto">col-auto</div>
        <div class="col-sm-9 bg-success">col-sm-3</div>
    </div>
</div>
&#13;
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';
&#13;
canvas {
  position:relative;
  width:48%;
  height:auto;
  float:left;
}
&#13;
&#13;
&#13;