簡體   English   中英

在一個畫布的角落內復制和粘貼一個畫布

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

我的HTML頁面上有兩個畫布,而我真正想做的是將所有內容粘貼到第二個畫布右下角的第一個畫布中。 這是我嘗試的代碼:

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

問題是:第二個畫布顯示圖像,但右下角不顯示第一個畫布。

值得的家伙,我需要答案。 這很重要。 感謝所有幫助者。

您在第二張畫布上繪制第一張畫布的方式不正確。 您可以使用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