JS canvas resizable cube
by bbauer
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="cubeSizeSelector">
<option>5x5</option>
<option>5x10</option>
<option>10x5</option>
</select>
<canvas></canvas>
CSS
canvas {
border: 1px solid #000;
}
select {
display: block;
}
JavaScript
var canvas = document.querySelector('canvas');
canvas.width = 500;
canvas.height = 300;
var contxt = canvas.getContext('2d');
function renderCube(height, width, depth, offsetX, offsetY) {
//clear possible existing cube
contxt.clearRect(0, 0, canvas.width, canvas.height);
contxt.beginPath();
// Calculate depth, width and height based on goven input
depth = depth * 10 * 0.8;
width = width * 10;
height = height * 10;
//squares
contxt.strokeStyle = 'grey';
var fillRect = false;
contxt.fillStyle = 'rgba(0, 0, 0, 0.2)';
contxt.rect(offsetX, offsetY, width, height);
contxt.rect((depth/2)+offsetX, offsetY-(depth/2), width, height);
if (fillRect) {
contxt.fill();
}
contxt.stroke();
//depth
contxt.moveTo(offsetX, offsetY);
contxt.lineTo(offsetX+(depth/2), offsetY-(depth/2));
contxt.moveTo(offsetX+width, offsetY);
contxt.lineTo(offsetX+width+(depth/2), offsetY-(depth/2));
contxt.moveTo(offsetX, offsetY+height);
contxt.lineTo(offsetX+(depth/2), offsetY+height-(depth/2));
contxt.moveTo(offsetX+width, offsetY+height);
contxt.lineTo(offsetX+width+(depth/2), offsetY+height-(depth/2));
contxt.stroke();
}
// Draw the cube initially with 5x5
renderCube(5, 5, 5, 100, 100);
// Add the onChange event listener to the select element
var cubeSizeSelector = document.getElementById('cubeSizeSelector');
cubeSizeSelector.onchange = function(e) {
var cubeSize = e.target.value.split('x');
renderCube(5, parseInt(cubeSize[0], 0), parseInt(cubeSize[1], 0), 100, 100);
}