Как заставить линии отображаться позади других вещей в HTML5 Canvas - PullRequest
0 голосов
/ 26 апреля 2019

Я пытался сделать визуализатор узлового графика, но у меня возникли проблемы с отображением линий за узловыми точками.Я уже пытался использовать context.globalCompositeOperation, но безрезультатно.Я попытался реализовать рендеринг в том порядке, в котором я хотел, чтобы он был нарисован.Вот полный код проекта:

var canvas = document.querySelector('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var c = canvas.getContext('2d');

var nodes = [];


var has_clicked = false;
var user_has_picked_up_object = false;
var picked_up_id;

class Vector2 {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
}

document.onmousemove = function(e){
    mouse_pos.x = e.pageX;
    mouse_pos.y = e.pageY;
}

document.onmousedown = function(e) {
    has_clicked = true;
}

document.addEventListener('mouseup', function(e) {
    has_clicked = false;
    user_has_picked_up_object = false;
})

var mouse_pos = new Vector2(0, 0);

class Connection {
    constructor(node1, node2) {
        this.node1 = node1;
        this.node2 = node2;
        this.isDrawn = false;
    }
}

function DistSQ(p1, p2) {
    return Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2);
}

class Node {
    constructor(pos, id) {
        this.pos = pos;
        this.radius = 10;
        this.radius_squared = 100;
        this.connections = [];
        this.id = id;
    }

    AddConnection(conn) {
        this.connections.push(conn);
    }
    RemoveConnection(conn) {
        return this.connections.pop(conn);
    }

    UpdatePosition() {
        if(DistSQ(this.pos, mouse_pos) < this.radius_squared && has_clicked) {
            if(user_has_picked_up_object && picked_up_id == this.id) {
                this.pos = mouse_pos;
            }
            else {
                user_has_picked_up_object = true;
                picked_up_id = this.id;
            }
        }
        else {
            this.pos = new Vector2(this.pos.x, this.pos.y);
        }
    }
}

function DrawLines(conns) {
    c.beginPath();
    c.lineWidth = 1;
    c.strokeStyle = 'black';
    conns.forEach(element => {
        c.moveTo(element.node1.pos.x, element.node1.pos.y);
        c.lineTo(element.node2.pos.x, element.node2.pos.y);
    });
    c.stroke();
}

function DrawCircles(nds) {
    c.beginPath();
    c.lineWidth = 1;
        nds.forEach(element => {
            c.strokeStyle = 'black';
            c.moveTo(element.pos.x+element.radius, element.pos.y);
            c.arc(element.pos.x, element.pos.y, element.radius, 0, 2 * Math.PI, false);
        });
    c.stroke();
}


function Update() {
    requestAnimationFrame(Update);

    c.clearRect(0, 0, window.innerWidth, window.innerHeight);
    for(var i = 0; i < nodes.length; i++) {
        nodes[i].UpdatePosition();
        DrawLines(nodes[i].connections);
    }
    DrawCircles(nodes);
}

function Initialize() {
    for(var y = 0, i = 0; y < 5; y++) {
        for(var x = 0; x < 5; x++, i++) {
            nodes.push(new Node(new Vector2(x*20+20, y*20+20), i));
        }
    }

    for(var i = 1; i < nodes.length; i++) {
        nodes[i].AddConnection(new Connection(nodes[i], nodes[i-1]));
    }
    Update();
}

Initialize();

1 Ответ

0 голосов
/ 26 апреля 2019

Спасибо @enxaneta, за то, что дали мне решение этой проблемы, поэтому я скопировал его ответ здесь: Линии находятся за кругами - В вашей функции DrawCircles добавьте c.fillStyle = "white";c.fill() - enxaneta

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...