简体   繁体   English

在一个画布的角落内复制和粘贴一个画布

[英]Copying and pasting one canvas inside another canvas's corner

I have two canvases on my HTML page and what i actually want to do is pasting all stuff inside first canvas in bottom right corner of second canvas. 我的HTML页面上有两个画布,而我真正想做的是将所有内容粘贴到第二个画布右下角的第一个画布中。 This is the code I was trying: 这是我尝试的代码:

<canvas id="first"></canvas>
<canvas id="second"></canvas>
<script>
var first = document.getElementById('first').getContext('2d');
var sec = document.getElementById('second').getContext('2d');

//--code for drawing in first canvas--

var img = new Image();
img.src="imgName.jpg";
img.onload = function() {
    sec.drawImage(img,0,0,sec.canvas.width,sec.canvas.height);

//Actually i want first canvas to overlap image on second canvas

    var paste = new Image();
    paste.src = first.canvas;
    paste.onload = function() {

        sec.drawImage(paste,100,100,400,600);

    };
};
</script>

Problem is: second canvas shows image but doesn't shows first canvas in its bottom right corner. 问题是:第二个画布显示图像,但右下角不显示第一个画布。

Please worthy guys, i need the answer. 值得的家伙,我需要答案。 Its very Important. 这很重要。 Thanks in advnce to all helpers.. 感谢所有帮助者。

The way you are drawing the first canvas on the second one is not correct. 您在第二张画布上绘制第一张画布的方式不正确。 You can directly draw a canvas on another canvas using drawImage() method. 您可以使用drawImage()方法在另一个画布上直接绘制一个画布。

 var first = document.getElementById('first').getContext('2d'); var sec = document.getElementById('second').getContext('2d'); // draw on first canvas first.fillStyle = '#07C'; first.fillRect(0, 0, first.canvas.width, first.canvas.height); // draw image on second canvas var img = new Image(); img.src = "http://lorempixel.com/300/300"; img.onload = function() { sec.drawImage(img, 0, 0, sec.canvas.width, sec.canvas.height); sec.drawImage(first.canvas, 100, 100, 100, 100); // draw first canvas on a portion of second canvas }; 
 body {display: flex} 
 <canvas id="first" width="200" height="200"></canvas> <canvas id="second" width="200" height="200"></canvas> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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