2012-10-03 36 views
0

我有2個畫布,canvas1和canvas2。兩者都很好,但我想將它們混合以導出爲圖像。 Overlay css based不起作用,因爲它打印2張圖像。任何一點開始?謝謝。畫布疊加輸出

<canvas id="canvas1" style="position:relative; float:left;border:1px solid #000 "  width="547" height="154"> 
</canvas> 

<canvas id="canvas2" style="z-index: 1; position:absolute; float:left;" width="547" height="500"> 
</canvas> 

回答

0

那麼,有幾種方法可以解決這個問題,你是什麼意思的混合?

如果您只是想在canvas1上疊加canvas2,但不想更改原始畫布,則可以將其數據發送到另一個畫布,然後獲取該數據。

方法如下:

draw canvas1 to canvas3 
draw canvas2 to canvas3 
get canvas3 image 

工作的javascript:

// Make all the canvas and context variables */ 
var c1 = document.getElementById('c1'); 
var c2 = document.getElementById('c2'); 
var c3 = document.getElementById('c3'); 
var c4 = document.getElementById('c4'); 

var ctx1 = c1.getContext('2d'); 
var ctx2 = c2.getContext('2d'); 
var ctx3 = c3.getContext('2d'); 
var ctx4 = c4.getContext('2d'); 
/* */ 

// Draw square on canvas 1 
ctx1.fillRect(0,0,50,50); 

// Draw offset square on canvas 2 
ctx2.fillRect(25,25,50,50); 

// Make third image and onload function 
var img3 = new Image(); 
img3.onload = function(){ 
    // Draw this image to canvas 4 so that we know it worked 
    ctx4.drawImage(this,0,0); 
} 

// So we know when both have loaded 
var imagesLoaded = 0; 
function draw(){ 
    // increment number loaded 
    imagesLoaded++; 

    // draw this image to canvas 3 
    ctx3.drawImage(this,0,0); 

    // if the have both loaded, then... 
    if (imagesLoaded == 2){ 

    // set third image's src to the canvas 3 image 
    img3.src = c3.toDataURL(); 
    } 

} 

// First image 
var img1 = new Image(); 
// So it will draw on canvas 3 
img1.onload = draw; 
// Set the src to canvas 1's image 
img1.src = c1.toDataURL(); 


// Second image 
var img2 = new Image(); 
// So it will draw on canvas 3 
img2.onload = draw; 
// Set the src to canvas 2's image 
img2.src = c2.toDataURL(); 

工作實例here

但是,如果這不是你正在尋找的,我很抱歉。