2013-11-24 169 views
1

我遇到問題我希望有人能夠幫助。HTML5畫布 - 分組/將圖像附加到畫布上

使用這種JSFIDDLE我可以按一個按鈕來新畫布添加到屏幕...

var next = 4 

    function addCanvas() { 
     // create a new canvas element 
     var newCanvas = document.createElement("canvas"); 
     newCanvas.id = "addedcanvases" + next; //added this to give each new canvas a unique id 
     next++; 
     newCanvas.width = canvasWidth; 
     newCanvas.height = canvasHeight; 
     // add a context for the new canvas to the contexts[] array 
     contexts.push(newCanvas.getContext("2d")); 
     // link the new canvas to its context in the contexts[] array 
     newCanvas.contextIndex = contexts.length; 
     // wire up the click handler 
     newCanvas.onclick = function (e) { 
      handleClick(e, this.contextIndex); 
     }; 
     // wire up the mousemove handler 
     newCanvas.onmousemove = function (e) { 
      handleMousemove(e, this.contextIndex); 
     }; 
     // add the new canvas to the page 
     document.body.appendChild(newCanvas); 
    } 

問題:

什麼是去的最佳途徑將靜態圖像分組/附加到畫布的頂部(如下圖所示),以便每當創建新畫布時,都會在JSFIDDLE圖像是自動創建的,它被分組/附加到新畫布的頂部。

這樣就可以在頁面上動態創建一個新的畫布,並將圖像放置在畫布上方?

canvas with image grouped/attached to the top of them

有可能做到這一點,我俯瞰明顯的方式?但是使用谷歌搜索並沒有引起太大反響,因爲所有的「圖像」和「畫布」搜索都不可避免地涉及到實際添加圖像到畫布上 - 這不是我想要在這種情況下做的。

您對我們的幫助是非常讚賞,感謝

回答

1

這裏的考慮@ KaliedaRik答案,並使用JavaScript創建組:

http://jsfiddle.net/m1erickson/3EUnc/

的代碼來創建新組可以是這樣的:

function newGroup(){ 

    // create a new wrapper div 
    var div=document.createElement("div"); 
    div.className="wrapper"; 

    // create an img and a canvas element 

    var img=document.createElement("img"); 
    var br=document.createElement("br"); 
    img.style.width="50px"; 
    img.src="houseicon.png"; 
    var canvas=document.createElement("canvas"); 
    canvas.width=300; 
    canvas.height=55; 

    // add the img and canvas elements to the wrapper div 

    div.appendChild(img); 
    div.appendChild(br); 
    div.appendChild(canvas); 

    // add the wrapper div with its contained img + canvas to the page 

    document.body.appendChild(div); 

} 
+0

優秀 - 完美的作品,並感謝評論。在每次添加新的畫布時,使畫布出現在彼此之下而不是彼此相鄰,直到以前使用頁面寬度爲止?非常感謝 –

+1

很高興我幫助了...如果你希望每個新組都位於前一組的右側,請查看CSS float:left指令:http://css-tricks.com/all-about-floats/ – markE

+0

感謝您的鏈接 - 圖像成功添加與畫布現在感謝 - http://jsfiddle.net/perl_user/TBh4k/ –

0

一個可能的解決方案:當您創建的canvas元素,創造在同一時間一個新的DIV,把帆布IMG標籤內它。通過使div位置風格相對,絕對包含canvas和img位置樣式,您可以將圖像放在任何需要的位置。

<div style="position: relative"> 
    <canvas style="position: absolute; top: 0px; left: 0px;"></canvas> 
    <img src="whatever" alt="whatever" style="position: absolute; top: -20px; left: 0px" /> 
</div> 
+0

我同意。 ..創建一個包裝img和canvas元素的div元素。由於圖像在畫布上靜態需要,因此您甚至不需要定位,只需(僞代碼):

。 – markE