JSFiddle - React, Tailwind, and code Playground
by Sukhmeet Singh
HTML
<center>
<canvas id="canvas" style="border: 2px solid black; cursor: crosshair;" width="1000" height="500"></canvas>
</center>
JavaScript
var canvas = document.getElementById("canvas")
var ctx = canvas.getContext("2d")
var w = canvas.width
var h = canvas.height
var d = 5; //distance to move on collision
var ball = []
var gravity = 0.3
var force = 0.2
var mouse = {
d: false,
x1: 0,
y1: 0,
x2: 0,
y2: 0,
}
window.onmousedown = function (e) {
mouse.d = true
mouse.x1 = mouse.x2 = e.pageX - canvas.getBoundingClientRect().left
mouse.y1 = mouse.y2 = e.pageY - canvas.getBoundingClientRect().top
}
window.onmousemove = function (e) {
if (mouse.d) {
mouse.x2 = e.pageX - canvas.getBoundingClientRect().left
mouse.y2 = e.pageY - canvas.getBoundingClientRect().top
} else {
mouse.x1 = mouse.x2 = e.pageX - canvas.getBoundingClientRect().left
mouse.y1 = mouse.y2 = e.pageY - canvas.getBoundingClientRect().top
}
}
window.onmouseup = function () {
if (mouse.d) {
mouse.d = false
var dx = (mouse.x1 - mouse.x2);
var dy = (mouse.y1 - mouse.y2);
var mag = Math.sqrt(dx * dx + dy * dy);
ball.push({
x: mouse.x1,
y: mouse.y1,
r: Math.floor(Math.random() * 20) + 10,
vx: dx / mag * -(mag * force),
vy: dy / mag * -(mag * force),
b: 0.7,
})
}
}
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
document.onselectstart = function () {
return false
}
document.oncontextmenu = function () {
return false
}
setInterval(update, 1000/60)
function update() {
ctx.clearRect(0, 0, w, h)
ctx.beginPath()
ctx.moveTo(mouse.x1, mouse.y1)
ctx.lineTo(mouse.x2, mouse.y2)
ctx.stroke()
ctx.closePath()
for (i = 0; i < ball.length; i++) {
ball[i].vy += gravity
ball[i].x += ball[i].vx
ball[i].y += ball[i].vy
if...