DEV Community

Spsoi
Spsoi

Posted on

3 2

HTML5 Javascript Canvas Collision

Читать снизу вверх

Статья будет дополнятся

//!* новые строки
Вычисляем пересечение двух кругов
jsfiddle.net

function animate() {
    requestAnimationFrame(animate); // каждую секунду отрисовываем
    c.clearRect(0,0, canvas.width, canvas.height); // удаляем предыдуший отрисованный кадр
    circle1.update();
    circle2.x = mouse.x;
    circle2.y = mouse.y;
    circle2.update();

    let distance = getDistance(circle1.x, circle1.y, circle2.x, circle2.y); // !*
    let touch = circle1.radius + circle2.radius;// !*
    console.log( touch); // !*
    if (distance < touch) { // !*
        circle1.color = 'red'; 
    } else { 
        circle1.color = 'black';
    }
    console.log(getDistance(circle1.x, circle1.y, circle2.x, circle2.y)); 

}
Enter fullscreen mode Exit fullscreen mode

Вычисляем расстояние курсора до центра первого шара (Чёрный).
jsfiddle.net

function getDistance(x1, y1, x2, y2) { //!* расчёт дистанции до центра первого круга
    let xDistance = x2 -x1; //!*
    let yDistance = y2 -y1; //!*

    let distance = Math.pow(xDistance, 2) + Math.pow(yDistance, 2); //!*// Теорема Пифагора

    return Math.sqrt(distance); //!*// квадратный корень числа
}

function animate() {
    requestAnimationFrame(animate); // каждую секунду отрисовываем
    c.clearRect(0,0, canvas.width, canvas.height); // удаляем предыдущий отрисованный кадр
    circle1.update();
    circle2.x = mouse.x;
    circle2.y = mouse.y;
    circle2.update();

    console.log(getDistance(circle1.x, circle1.y, circle2.x, circle2.y)); //!* 

}

Enter fullscreen mode Exit fullscreen mode

Отрисуем второй шарик прям.
jsfiddle.net

let circle1 ;
let circle2 ; //!*
function init() { // точка входа
    //1
    circle1 = new Circle(300, 300, 100, 'black');
    circle2 = new Circle(undefined, undefined, 30, 'red'); //!*
}

function animate() {
    requestAnimationFrame(animate); // каждую секунду отрисовываем
    c.clearRect(0,0, canvas.width, canvas.height); // удаляем предыдущий от рисованный кадр
    circle1.update();
    circle2.x = mouse.x; //!*
    circle2.y = mouse.y; //!*
    circle2.update(); //!*
}
Enter fullscreen mode Exit fullscreen mode

Отрисуем шар в центре канваса
jsfiddle.net

canvas = document.querySelector('#canvas');
let c = canvas.getContext('2d');

canvas.width = innerWidth;
canvas.height = innerHeight;

let mouse = {
    x: innerWidth / 2,
    y: innerHeight / 2
}

let colors = [
    '#2185c5',
    '#7ECEFD',
    '#FFF6E5',
    '#FF7F66'
];

document.addEventListener("mousemove", function(event){
    mouse.x = event.clientX;
    mouse.y = event.clientY;
});

addEventListener("resize", function(){ // при изменении окна растягиваем окно canvas
    canvas.width = innerWidth;
    canvas.height = innerHeight;
    // init();
});

function randomIntFromRange(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
}

function randomColor (color){
    return color[Math.floor(Math.random() * color.length)];
}

addEventListener("click", function () { // клик по экрану сбрасывает анимацию
    init();
})


function Circle (x, y, radius, color) { // шарик
    // 2
    this.x =x;
    this.y = y;
    this.radius = radius;
    this.color = color;

    this.update = function() {
        this.draw();
    }

    this.draw = function () {
        c.beginPath();
            c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
            c.fillStyle = this.color;
            c.fill();
            c.stroke();
        c.closePath();
    }
}

let ballArray;
let circle1 ;
function init() { // точка входа
    //1
    circle1 = new Circle(300, 300, 100, 'black');
}

function animate() {
    requestAnimationFrame(animate); // каждую секунду отрисовываем
    c.clearRect(0,0, canvas.width, canvas.height); // удаляем предыдуший отрисованный кадр
    circle1.update();
}

init();
animate();
Enter fullscreen mode Exit fullscreen mode

style.css

canvas {
    border: 1px solid #000;
}
Enter fullscreen mode Exit fullscreen mode

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    <canvas id="canvas" width="300" height="300"></canvas>
    <script  src="canvas.js" ></script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more