JSFiddle - React, Tailwind, and code Playground
by tiagoa
HTML
<html>
<head>
<script type="text/javascript" src="desenha.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Movimento</title>
<style type="text/css">
body{
padding:20px;
background:#ccc;
margin:0;
}
</style>
</head>
<body onload="desenha()">
<canvas id="canvas" width="400" height="300" style="border:1px solid #aaa;"></canvas>
</body>
</html>
JavaScript
//SETUP
var tx = 400; //LARGURA TOTAL
var ty = 300; //ALTURA TOTAL
var t = 1; //TAMANHO DE CADA PONTO
//CARINHA
var tam = 4; //TAMANHO DA BOLINHA
var tamPopulacao = 150; //TAMANHO DA POPULAÇÃO
var visao = 5;
var bolinhaDesenhadas = [];
function getP() {
var x = Math.floor(Math.random() * tx-tam);
var y = Math.floor(Math.random() * ty-tam);
var x1 = x-tam;
var x2 = x1+tam*2;
var y1 = y-tam;
var y2 = y1+tam*2;
for(var i = 0; i < bolinhaDesenhadas.length; i++) {
var b = bolinhaDesenhadas[i];
var colisaox = x1 > b.x1 && x1 < b.x2 || x2 > b.x1 && x2 < b.x2;
var colisaoy = y1 > b.y1 && y1 < b.y2 || y2 > b.y1 && y2 < b.y2;
if (colisaox && colisaoy) {
return getP();
}
}
bolinhaDesenhadas.push({x1, x2, y1, y2});
return {x, y};
}
function desenha() {
var canvas = document.getElementById("canvas");
var desenho = canvas.getContext("2d");
//MAPA *************************************************
desenho.beginPath();
desenho.rect(0, 0, tx, ty);
desenho.fillStyle = "white";
desenho.fill();
//MAPA *************************************************
//BOLINA ***********************************************
for(i=1;i<=tamPopulacao;i++){
//POSIÇÃO
var p = getP();
var startAngle = 0;
var endAngle = 3.5 * Math.PI;
//DESENHAR
desenho.beginPath();
desenho.arc(p.x, p.y, tam, 0, Math.PI * 2, true);
desenho.fillStyle = "#e87e04";
desenho.fill();
}
//BOLINA ***********************************************
}