Created
August 9, 2018 01:35
-
-
Save iamsainikhil/8d04605520ee0b1462fc8bfa38064e47 to your computer and use it in GitHub Desktop.
Randomly Generated Canvas Figures
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Random Figures</title> | |
<style> | |
.canvas-wrapper { | |
display: flex; | |
margin: 10px auto; | |
} | |
#playground:hover { | |
cursor: pointer; | |
} | |
</style> | |
</head> | |
<body> | |
<div class="canvas-wrapper"> | |
<canvas id="playground"></canvas> | |
</div> | |
<script> | |
var canvas = document.getElementById('playground'); | |
var ctx = canvas.getContext('2d'); | |
function randomColor() { | |
var letters = '0123456789ABCDEF'; | |
var color = '#'; | |
for (var i = 0; i < 6; i++) { | |
color += letters[Math.floor(Math.random() * 16)]; | |
} | |
return color; | |
} | |
function randomNumber(limit) { | |
const n = Math.floor(Math.random() * limit); | |
return n; | |
} | |
function drawRectangle() { | |
ctx.fillStyle = randomColor(); | |
ctx.fillRect(50, 50, 200, 150); | |
} | |
function drawSquare() { | |
ctx.fillStyle = randomColor(); | |
ctx.fillRect(50, 50, 100, 100); | |
} | |
function drawCircle() { | |
ctx.fillStyle = randomColor(); | |
ctx.strokeStyle = ctx.fillStyle; | |
ctx.beginPath(); | |
ctx.arc(50, 100, 50,0, 2*Math.PI); | |
ctx.stroke(); | |
ctx.fill(); | |
} | |
function randomFigure() { | |
// to clear canvas everytime before it is re-rendered | |
canvas.width = canvas.width; | |
// to translate canvas to random x and y co-ordinates | |
canvas.style.transform = `translate(${randomNumber(250)}px, ${randomNumber(250)}px)`; | |
const number = Math.floor(Math.random() * 3); | |
if (number === 0) { | |
drawRectangle(); | |
} else if (number === 1) { | |
drawCircle(); | |
} else { | |
drawSquare(); | |
} | |
} | |
setInterval(randomFigure, 1000); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment