使用JavaScript将元素放置到画布上

时间:2015-06-08 13:50:45

标签: javascript html

我正在做一个小游戏。我会将一些div - 标记放入canvas - 标记中。这是我的代码:

document.addEventListener("DOMContentLoaded", function () {
    init();
});

function init(){
    draw();
}

function draw(){

    var number = Math.round((Math.random() * 31) + 20);
    var cnv = document.getElementsByTagName("canvas")[0];

    for (i = 0; i <= number ; i++){

        var div = document.createElement('div');

        //breedte
        var length = Math.round((Math.random() * 31) + 20);
        div.style.height = length + "px";
        div.style.width = length + "px";

        //locattie
        div.style.top = Math.floor(Math.random() * (cnv.height - 100))+ "px";
        div.style.left = Math.floor(Math.random() * (cnv.width - 100))+ "px";

        //toevoegen
        div.style.backgroundColor = "rgb(" + Math.floor(Math.random() * 255) + ", " + Math.floor(Math.random() * 255) + ", " + Math.floor(Math.random() * 255) + ")";

        cnv.appendChild(div);
    }
}
canvas{
    width: 100%;
    height: 500px;
    background-color: #898989;
}

div {
    position: absolute;
}
<canvas id="playarea">
</canvas>

所以你可以看到,它只显示一个空的canvas。只有实现元素,我才能看到生成的div - 标签。我也尝试在我的div的CSS代码中替换一些属性。但它不起作用......

任何人都可以帮助我吗?感谢

2 个答案:

答案 0 :(得分:3)

canvas并非打算封装div - 就像这样。您应该尝试使用本地画布方法,例如fillRect()see this MDN tutorial

快速举例:

document.addEventListener("DOMContentLoaded", function () {
    init();
});

function init(){
    draw();
}

function draw(){

var number = Math.round((Math.random() * 31) + 20);
var cnv = document.getElementsByTagName("canvas")[0];
var ctx = cnv.getContext("2d");
var top = 0;
var left = 0;
var size = 0;

for (i = 0; i <= number ; i++){

    ctx.fillStyle = "rgb(" + Math.floor(Math.random() * 255) + ", " + Math.floor(Math.random() * 255) + ", " + Math.floor(Math.random() * 255) + ")";

    top = Math.floor(Math.random() * (cnv.height - 100));
    left = Math.floor(Math.random() * (cnv.width - 100));
    size = Math.round((Math.random() * 31) + 20);

    ctx.fillRect(left, top, size, size);

    }
}

答案 1 :(得分:2)

画布对象中的节点只会在不支持画布元素的浏览器中显示:

<canvas>Your browser <em>doesn't</em> support the canvas element!</canvas>

如果你想在画布上添加元素,可以考虑添加一个包装器并将元素添加到它:

<div class="canvas_wrapper">
  <canvas></canvas>
  <div class="canvas_child">My added element</div>
</div>

还有一些像这样的CSS:

.canvas_wrapper { position: relative; }
.canvas_child { position: absolute; top: 100px; left: 100px; }
相关问题