簡體   English   中英

畫布:將照片綁定到框架中

[英]canvas: bind photo into the frame

美好的一天!

合並畫布圖像時出現問題。 我認為這些問題將被標記為答復,但我沒有找到解決問題的方法。

所以這筆交易:獲得3個畫布-1和2是圖像(我認為必須隱藏),3-合並的畫布。 1是框架 ,2是照片 ,照片必須框架 (在css中,我可以使用z-index )。

HTML:

<div class="container">

    <canvas id="first" width="400" height="400"></canvas>

    <canvas id="second" width="200" height="200"></canvas>

    <canvas id="third" width="400" height="400"></canvas>

</div>

JS:

var imgFirst = document.getElementById("first");
ctx1 = imgFirst.getContext('2d');
pic1 = new Image();
pic1.src = "http://www.deftune.com/wp-content/uploads/2010/10/thexx-400x400.jpg";


var imgSecond = document.getElementById("second");
ctx2 = imgSecond.getContext('2d');
pic2 = new Image();
pic2.src = "http://tech21info.com/admin/wp-content/uploads/2013/03/chrome-logo-200x200.png";

var imgThird = document.getElementById('third');
ctx3 = imgThird.getContext('2d');
pic1.onload = function() {
    pic2.onload = function() {
        ctx3.drawImage(pic1, 0, 0, 400, 400);
        ctx3.drawImage(pic2, 100, 100, 200, 200);
    };
};

我有jsfiddle示例: http : //jsfiddle.net/hh6ovneq/3/但它不起作用

有幾件事可以大大簡化您的代碼。 首先,由於您僅加載圖像資源,請改用img標簽。 然后創建一個回調函數,並在兩個圖像都加載后觸發它。

由於我不清楚您的照片是什么,框架是什么,我目前使用的是相反的順序,但是只需切換兩個drawImage函數即可切換其順序(或z-index,無論您要描述什么)。 但是,由於頂部圖像沒有透明值,因此當像素被新顏色覆蓋時,它將隱藏底部圖像。

結果看起來像這樣,看起來更干凈,更易讀:

 // Get all your images. var first = document.getElementById('first'); var second = document.getElementById('second'); // get canvas and context var result = document.getElementById('result'); var context = result.getContext('2d'); // create a counter to make sure all images are loaded before drawing var loaded = 0; // something to execute when loading of images has completed function combine(){ // The order of drawing will be the order of layers // The final two arguments define the size of what you want to draw context.drawImage(second, 0, 0, 400, 400); context.drawImage(first, 100, 100, 200, 200); } // Add event listeners to the images first.addEventListener('load', function(){ // increase the loaded number loaded++; // hide the image first.style.display = 'none'; // if loaded hits the total number of images, use the completion function if(loaded === 2) combine(); }, false); // (wrince, repeat for image 2) second.addEventListener('load', function(){ loaded++; second.style.display = 'none'; if(loaded === 2) combine(); }, false); 
 <div class="container"> <img id="first" width="400" height="400" src="http://www.deftune.com/wp-content/uploads/2010/10/thexx-400x400.jpg" /> <img id="second" width="200" height="200" src="http://tech21info.com/admin/wp-content/uploads/2013/03/chrome-logo-200x200.png" /> <canvas id="result" width="400" height="400"></canvas> </div> 

最后,我想補充一點,當在第二張圖像之前加載第二張圖像時,嵌套的onload函數可能會適得其反,這意味着load事件不再觸發。 使用單獨的加載並計數它們,以確保結果正確。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM