JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="drawingCanvas" class="main-canvas">
</canvas>
<button id="drawSquareButton" class="draw-square-button" onclick="randomizeSquare();">
Draw Square
</button>
CSS
.main-canvas {
height: 200px;
width: 500px;
border: 1px solid #dddddd;
margin: auto;
}
JavaScript
function drawSquare(x, y, width, height) {
var canvas = document.getElementById("drawingCanvas");
var canvasContext = canvas.getContext("2d");
canvasContext.clearRect ( 0 , 0 , canvas.width, canvas.height );
canvasContext.fillStyle = "#000000";
canvasContext.fillRect(x, y, width, height);
}
function randomizeSquare() {
var canvas = document.getElementById("drawingCanvas");
// Get width of the canvas.
var canvasWidth = canvas.width;
// Get height of the canvas.
var canvasHeight = canvas.height;
var x = Math.floor(Math.random() * (canvasWidth + 1));
var y = Math.floor(Math.random() * (canvasHeight + 1));
var width = Math.floor(Math.random() * (canvasWidth - x - 5));
var height = Math.floor(Math.random() * (canvasHeight - y - 5));
// Draw the square with our generated parameters.
drawSquare(x, y, height, width);
}