Skip to content

Instantly share code, notes, and snippets.

@Joezo
Created July 15, 2016 13:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Joezo/f4a9f80c1580b6c06280cbc4e0aea9ca to your computer and use it in GitHub Desktop.
Save Joezo/f4a9f80c1580b6c06280cbc4e0aea9ca to your computer and use it in GitHub Desktop.
Drawing colourful squares with JS
<html>
<head>
<title>Colours</title>
</head>
<body>
<canvas id="myCanvas"></canvas>
<script type="text/javascript">
var canvas = document.getElementById('myCanvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var canvasContext = canvas.getContext('2d');
var colours = [
'#7FDBFF','#0074D9','#001F3F','#39CCCC','#2ECC40','#3D9970',
'#01FF70','#FFDC00','#FF851B','#FF4136','#F012BE','#B10DC9','#85144B',
];
var drawMosaic = function(canvas, canvasContext){
var tilesTop = 0;
var tilesLeft = 0;
var tileSize = 40;
var tileCountLeft = 35;
var tileCountTop = 55;
canvasContext.beginPath();
for(var x=0; x<2000; x++){
canvasContext.fillStyle = colours[Math.floor(Math.random() * colours.length)];
canvasContext.fillRect(tilesTop * tileSize,tilesLeft*tileSize,tileSize,tileSize);
if(tilesTop < tileCountTop){
tilesTop++;
} else {
tilesTop = 0;
tilesLeft++;
}
if(tilesLeft == tileCountLeft){
break;
}
}
}
var fps = 2;
var fpsInterval=1000/fps;
var then=Date.now();
var startTime=then;
var animate = function(canvas, context){
requestAnimationFrame(function(){
animate(canvas, context);
});
var now = Date.now();
var elapsed = now - then;
// if enough time has elapsed, draw the next frame
if (elapsed > fpsInterval) {
// Get ready for next frame by setting then=now, but also adjust for your
// specified fpsInterval not being a multiple of RAF's interval (16.7ms)
then = now - (elapsed % fpsInterval);
// Put your drawing code here
context.clearRect(0,0,canvas.width, canvas.height);
drawMosaic(canvas, context);
}
}
drawMosaic(canvas, canvasContext);
setTimeout(function(){
animate(canvas, canvasContext);
},1000);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment