Skip to content

Instantly share code, notes, and snippets.

@rafinskipg
Created March 6, 2020 06:58
Show Gist options
  • Save rafinskipg/1865fe53daccf62b1f2b319050aa4410 to your computer and use it in GitHub Desktop.
Save rafinskipg/1865fe53daccf62b1f2b319050aa4410 to your computer and use it in GitHub Desktop.
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
const totalFigures = 50
const figures = []
function drawSquare(x, y, size, angleOfRotation) {
// Store the painting state in a stack
context.save()
// We get the radians from a degree
const radians = Utils.degreeToRadian(angleOfRotation);
// Translate in the context the origin of coordinates
context.translate(x, y);
// Rotate the context
context.rotate(radians);
// Draw a square
context.beginPath();
context.rect(-Math.round(size/2), -Math.round(size/2), size, size);
context.stroke();
context.fillStyle = Utils.randomColor();
context.fill();
// Paint a text indicating the degree of rotation (at 0, 0 because we have translate the coordinates origin)
context.fillStyle = 'black';
context.fillText(angleOfRotation, 0 , 0 );
// Restore the state of the context from the stack
context.restore()
}
function createFigures() {
for(var i = 0; i<totalFigures; i++) {
figures.push({
x: Utils.randomInteger(0, 560),
y: Utils.randomInteger(0, 560),
size: Utils.randomInteger(20, 100),
angle: Utils.randomInteger(0, 360)
})
}
}
function maximizeCanvas() {
canvas.width = window.innerWidth
canvas.height = window.innerHeight
}
function render() {
maximizeCanvas()
createFigures()
figures.map(square => {
drawSquare(square.x, square.y, square.size, square.angle)
})
}
render();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment