简体   繁体   中英

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. 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.

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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