2013-11-24 173 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