简体   繁体   English

在页面上动态创建框

[英]Create Boxes Dynamically on a Page

I am having trouble adding boxes dynamically to an HTML canvas. 我在将框动态添加到HTML画布时遇到麻烦。 There should be a random amount of boxes, in random positions, of random colors. 在随机位置应有随机数量的随机颜色的盒子。 The goal of what I am doing with the boxes is to be able to move them. 我正在使用盒子的目的是要能够移动它们。 Essentially I am really lost. 本质上我真的迷路了。

Here is the html code: 这是html代码:

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

    <body>      
    </body>
</html>

Here is the Javascript code: 这是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);
}

Nothing is showing up on the page, through debugging it seems it is having issues with the properties. 该页面上没有任何显示,通过调试,似乎属性有问题。 I am not sure where to go from here. 我不确定从这里去哪里。

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

context.fillStyle = colour;

你的意思是

context.fillStyle = boxes[i].colour;

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

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