我无法将框动态添加到 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);
}
页面上没有显示任何内容,通过调试似乎属性有问题。我不知道从这里去哪里。