Created
March 6, 2020 07:31
-
-
Save rafinskipg/fd40c707e4328f14d01e899d97f5e471 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const canvas = document.getElementById('canvas'); | |
const context = canvas.getContext('2d'); | |
let before = Date.now() | |
let dt = 0 | |
const totalFigures = 50 | |
const figures = [] | |
function drawSquare(square) { | |
// Store the painting state in a stack | |
context.save() | |
// We get the radians from a degree | |
const radians = Utils.degreeToRadian(square.angle); | |
// Translate in the context the origin of coordinates | |
context.translate(square.x, square.y); | |
// Rotate the context | |
context.rotate(radians); | |
// Draw a square | |
context.beginPath(); | |
context.rect(-Math.round(square.size/2), -Math.round(square.size/2), square.size, square.size); | |
context.stroke(); | |
context.fillStyle = square.color; | |
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(square.angle, 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), | |
color: Utils.randomColor(), | |
size: Utils.randomInteger(20, 100), | |
angle: Utils.randomInteger(0, 360) | |
}) | |
} | |
} | |
function maximizeCanvas() { | |
canvas.width = window.innerWidth | |
canvas.height = window.innerHeight | |
} | |
function update(dt) { | |
const speed = 100 // We can have a different speed per square if we want | |
// We are updating only the X position | |
figures.forEach(figure => { | |
figure.x = figure.x + (dt * speed ) > canvas.width ? 0 : figure.x + (dt * speed) | |
}) | |
} | |
function render() { | |
figures.map(square => { | |
drawSquare(square) | |
}) | |
} | |
function clear() { | |
context.clearRect(0, 0, canvas.width, canvas.height) | |
} | |
function loop() { | |
const now = Date.now() | |
dt = (now - before) / 1000 | |
clear() | |
update(dt) | |
render() | |
before = now | |
window.requestAnimationFrame(loop) | |
} | |
// Initialize everything | |
createFigures() | |
maximizeCanvas() | |
loop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment