Playable code
HTML
<!-- Learn about this code on MDN: https://developer.mozilla.org/ru/docs/Web/API/CanvasRenderingContext2D/clearRect -->
<div class="CanvasContainer" id="CanvasContainer" style="">
<!-- <img id="pic" src="https://img.hotels24.ua/photos/ria/new_images/1123/112317/11231753/11231753m.jpg" width="600" style=""> -->
<canvas id="drawingCanvas" width="600" height="375" style="position:absolute; left: 8px; top: 8px"></canvas>
</div>
CSS
canvas {
border: 1px solid black;
}
JavaScript
var canvas;
var context;
var lines = [];
var r = 255;
var g = 0;
var b = 0;
var mouse_x;
var mouse_y;
var repel_radius = 60;
function LineObject(pos_x, pos_y, size) {
this.pos_x = pos_x;
this.pos_y = pos_y;
this.width = 2;
this.size = size;
this.speed = 2;
this.addheight = Math.sin(Math.PI / 4) * (this.size / 2);
this.draw = function() {
context.beginPath();
context.lineWidth = 3;
context.strokeStyle = 'rgb(' + r + ',' + g + ',' + b + ')';
context.moveTo(this.pos_x, this.pos_y + this.size);
context.lineTo(this.pos_x, this.pos_y);
context.stroke();
}
}
function init() {
canvas = document.getElementById("drawingCanvas");
canvas.addEventListener("mousemove", function(e) {
mouse_x = e.clientX;
mouse_y = e.clientY;
});
context = canvas.getContext("2d");
lines.push(new LineObject(290, 0, 10));
lines.push(new LineObject(290, 0, 10));
lines.push(new LineObject(480, 80, 15));
lines.push(new LineObject(50, 150, 5));
lines.push(new LineObject(300, 200, 5));
lines.push(new LineObject(100, 65, 5));
lines.push(new LineObject(10, 5, 5));
lines.push(new LineObject(150, 85, 5));
lines.push(new LineObject(250, 105, 5));
}
function repel(x, y, radius) {
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
var line_pos_y = line.pos_y;
var above = false;
if (line_pos_y < y) {
line_pos_y += line.size;
above = true;
}
// math comes from here: https://math.stackexchange.com/a/127615/91283
var distance = Math.sqrt(Math.pow(x - line.pos_x, 2) + Math.pow(y - line_pos_y, 2));
if (radius > distance) {
line.pos_x = x + radius * (line.pos_x - x) / distance;
line.pos_y = y + radius * (line_pos_y - y) / distance;
if (above) {
line.pos_y -= line.size;
}
...