在页面上动态创建框

时间:2013-10-19 20:35:59

标签: javascript html

我无法动态地将框添加到HTML画布。随机颜色的随机位置应该有随机数量的盒子。 我正在用盒子做的目标是能够移动它们。 基本上我真的迷路了。

这是html代码:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Ramdom Boxes</title>
        <script src="A2Q1.js"></script>
    </head>

    <body>      
    </body>
</html>

以下是Javascript代码:

window.onload = init;

function init() {
    //when page is loaded create a bunch of boxes randomly throughout the page
    //get the body element of the document
    var body = document.getElementsByTagName("body")[0];

    //create the canvas tag
    var canvas = document.createElement("canvas");
    canvas.height = 666;
    canvas.width = 1346;
    var context = canvas.getContext("2d");

    //create the random boxes and append onto the canvas
    var randNum = Math.floor(Math.random() * 1000 + 1);

    var boxes = [];
    for(var i=0;i<randNum;i++){
        boxes[i].height = 50;
        boxes[i].width = 50;
        boxes[i].x = Math.floor(Math.random() * (1346 - boxes[i].width));
        boxes[i].y = Math.floor(Math.random() * (666 - boxes[i].height));

        boxes[i].colour = '#'+ Math.round(0xffffff * Math.random()).toString(16);
    }

    for(var i=0;i<boxes.length;i++){
        context.fillStyle = colour;
        context.fillRect(boxes[i].x, boxes[i].y, , boxes[i].height); 
    }

    //append the canvas onto the body 
    body.appendChild(canvas);
}

页面上没有任何内容显示,通过调试它似乎与属性有关。我不知道从哪里开始。

2 个答案:

答案 0 :(得分:0)

您可以使用masonry jquery插件对框进行排序。

答案 1 :(得分:0)

context.fillStyle = colour;

你的意思是

context.fillStyle = boxes[i].colour;