I’m trying to implement a function in javascript that will do the following:
Allow the user to specify the number of input rectangles (between 3 and 30).
Generate the requested number of input rectangles (with random widths and heights) and write them to a file (human readable).
Read the randomly generated input rectangles from the file generated in the step above.
Display the input rectangles graphically, correctly laid out, as in the example.
Calculate the output rectangles.
Display the output rectangles graphically, correctly laid out as in the example above. Note: Both the input and output rectangles must be displayed at the same time.
Write the output rectangle coordinates into an output file (human readable).
Input:
A random set of rectangles placed next to each other, from left to right, on the same baseline.
Output:
Output the minimum number of vertically stacked rectangles that represents the same area and resulting shape as described by the input rectangles.
A the moment this below is where I stand, I found a part of this code but now I’m stuck and can’t get it to work with all this implementations, how can I add input value from 3 to 30? how the result will display input and output at the same time?
Any hint is truly appreciated.
<script>
function doit() {
drawRectangle(100, 150, 200, 100);
myrect = document.getElementById("newdiv");
myrect.innerHTML= myrect.innerHTML + "<h1>howto</h1>";
}
function drawRectangle(left, top, width, height) {
if (document.createElement) {
newdiv=document.createElement("div");
newdiv.style.position="absolute";
newdiv.style.left = left+"px";
newdiv.style.top = top+"px";
newdiv.style.width = width+"px";
newdiv.style.height = height+"px";
newdiv.style.backgroundColor = 'red';
newdiv.style.visibility = 'visible';
newdiv.id = 'newdiv';
newdiv.innerHTML = "real";
document.body.appendChild(newdiv);
}
}
</script>
I created a JSFiddle for you to show a basic starting point using your existing code and for you to play around in if you want. I added a
<input>element to allow you to specify the number of rectangles to draw. However, I leave it up to you to change yourdoitmethod to actually draw more rectangles.As for the geometry question of determining larger rectanlges to fill the space of all the smaller rectanlges, see this SO question.
You may also want to think about using the
canvasto draw the rectangles instead ofdivelements as it will be much easier to draw larger numbers of them and to separate the output and input rectangles.. A nice basic tutorial can be found here.