How to draw a cube in 2D, canvas
I did not find these formulas on the Internet.
HTML code:
<p>Width:
<SELECT name = 'width' id = 'width' onchange = 'render();'>
<OPTION value = '100' selected> 100cm </OPTION>
<OPTION value = '110'> 110cm </OPTION>
<OPTION value = '120'> 120cm </OPTION>
</SELECT> </p>
<p>Depth:
<SELECT name = 'depth' id = 'depth' onchange = 'render();'>
<OPTION value = '50' selected> 50cm </OPTION>
<OPTION value = '60'> 60cm </OPTION>
<OPTION value = '70'> 70cm </OPTION>
</SELECT> </p>
<p>Height:
<SELECT name = 'height' id = 'height' onchange = 'render();'>
<OPTION value = '100' selected> 100cm </OPTION>
<OPTION value = '110'> 110cm </OPTION>
<OPTION value = '120'> 120cm </OPTION>
</SELECT> </p>
<h3> Model according to your parameters </h3>
<canvas id = "my-house" width = "300" height = "240" class = 'background-white'></canvas>
Javascript:
function render() {
const canvas = document.getElementById ('my-house');
const ctx = canvas.getContext ('2d');
var width_canvas = 300;
var height_canvas = 240;
const context = canvas.getContext ('2d');
context.clearRect (0, 0, width_canvas, height_canvas);
var x = document.getElementById ("width". value;
x = parseInt (x, 10);
var y = document.getElementById ("depth". value;
y = parseInt (y, 10);
var z = document.getElementById ("height". value;
z = parseInt (z, 10);
var start_x = (width_canvas - x) / 2;
var start_y = (height_canvas -z) / 2;
// Set line width
ctx.lineWidth = 2;
// Wall
ctx.setLineDash ([]); // solid line
ctx.strokeRect (start_x, start_y, x, z);
ctx.setLineDash ([6, 6]);
// first corner top left
ctx.beginPath ();
ctx.moveTo (start_x, start_y);
ctx.lineTo (start_x + y / 2, start_y-y / 2);
ctx.stroke ();
// line up
ctx.beginPath ();
ctx.moveTo (start_x + y / 2, start_y-y / 2);
ctx.lineTo (start_x + x + y / 2, start_y-y / 2);
ctx.stroke ();
//at the top right
ctx.beginPath ();
ctx.moveTo (start_x + x, start_y);
ctx.lineTo (start_x + x + y / 2, start_y-y / 2);
ctx.stroke ();
// bottom right
ctx.beginPath ();
ctx.moveTo (start_x + x, start_y + z);
ctx.lineTo (start_x + x + y / 2, start_y + z-y / 2);
ctx.stroke ();
//right
ctx.beginPath ();
ctx.moveTo (start_x + x + y / 2, start_y + z-y / 2);
ctx.lineTo (start_x + x + y / 2, start_y-y / 2);
ctx.stroke ();
//left
ctx.beginPath ();
ctx.moveTo (start_x + y / 2, start_y + z-y / 2);
ctx.lineTo (start_x + y / 2, start_y-y / 2);
ctx.stroke ();
// corner inside left
ctx.beginPath ();
ctx.moveTo (start_x, start_y + z);
ctx.lineTo (start_x + y / 2, start_y + z-y / 2);
ctx.stroke ();
// inside down
ctx.beginPath ();
ctx.moveTo (start_x + y / 2, start_y + z-y / 2);
ctx.lineTo (start_x + x + y / 2, start_y + z-y / 2);
ctx.stroke ();
}render();
RESULT: