JSFiddle - React, Tailwind, and code Playground
by anothernick
HTML
<div id="cwrap">
<canvas id="canvas" width="800" height="600"></canvas>
</div>
CSS
#canvas{
box-shadow: 0 0 4px #000;
margin: auto;
display:block;
}
#cwrap{
width:100%;
}
JavaScript
$(document).ready(function() {
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var pixels = [];
var mRadius = 40;
var y = 200;
while( y-- )
{
if( y % 5 == 0 )
{
var x = 200;
while( x-- )
{
if( x % 5 == 0 ){
var px = {
height: 5,
width: 5,
mass: 1,
home: {xpos: x, ypos: y},
realpos: {xpos: x, ypos: y},
acc: {x: 0, y:0}
};
pixels[pixels.length] = px;
}
}
}
}
var Mouse = { //make a globally available object with x,y attributes
x: 0,
y: 0
}
canvas.onmousemove = function (event) { // this object refers to canvas object
Mouse = {
x: event.pageX - this.offsetLeft,
y: event.pageY - this.offsetTop
}
}
// Draw the Foreground Canvas
setInterval(function(){
canvas.width = canvas.width;
for(var i = 0; i < pixels.length; i++)
{
checkCollision(i);
var pix = pixels[i];
context.fillRect(pix.realpos.xpos, pix.realpos.ypos, 2, 2);
}
context.fillStyle = "transparent";
context.beginPath();
context.moveTo(Mouse.x, Mouse.y);
context.arc(Mouse.x, Mouse.y, mRadius, 0, Math.PI*2, false);
context.fill();
}, 33);
function checkCollision(i){
var mx = Mouse.x;
var my = Mouse.y;
//(x2-x1)^2 + (y1-y2)^2 <= (r1+r2)^2
var distance_from_mouse = Math.sqrt( Math.pow((my - pixels[i].realpos.ypos), 2) + Math.pow((mx - pixels[i].realpos.xpos), 2) );
if(distance_from_mouse <= mRadius){
...