繁体   English   中英

HTML5 Canvas - 将图像分组/附加到画布

[英]HTML5 Canvas - Grouping / Attaching an image TO a canvas

使用这个JS Fiddle我可以按下一个按钮来向屏幕添加新的画布......

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);
    }

问题:

静态图像分组/附加到画布顶部的最佳方法是什么(如下图所示),以便每当在JS Fiddle 中创建新画布时,都会自动创建一个图像,并将其分组/附加到新画布的顶部。

这样一来,无论何时在页面上动态创建新画布,都会将图像放在该画布上方?

带有图像分组/附加到其顶部的画布

可能有一种明显的方法可以做到这一点,但我忽略了? 但是谷歌搜索并没有抛出太多,因为所有“图像”和“画布”搜索不可避免地与实际将图像添加到画布相关 - 在这种情况下,这不是我想要做的。

以下是@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);

}

一种可能的解决方案:在创建canvas元素时,同时创建一个新的div ,并将canvasimg标签放入其中。 通过使 div 位置样式相对,并将包含的画布和 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM