Connecting two elements using a line/wire manually

时间:2017-12-18 07:29:06

标签: javascript html5 html5-canvas

I want the user to be able to connect a set of points using a wire or line. Connection is complete when points 1, 2 and 6 are connected, otherwise if player makes wrong connections then screen shows wrong connections.

1 个答案:

答案 0 :(得分:0)

我可以给出一些指示。

线描

在选择节点时,您可以在其他节点上绘制线条和放置。继续捕获节点ID,如果列表有1,2,6说明其正确或错误

function drawLine(x, y) {
    ctx.beginPath();
    ctx.moveTo(startX, startY);
    ctx.lineTo(x, y);
    ctx.closePath();
    ctx.stroke();
    ctx.restore();
}

canvas.onmousedown = function (e)  {
    ctx.save();
    e.preventDefault();
    e.stopPropagation();
    startX = parseInt(e.clientX - offsetX);
    startY = parseInt(e.clientY - offsetY);
    isDown = true;
}
canvas.onmousemove = function (e)  {
    if (!isDown) {
        return;
    }
    e.preventDefault();
    e.stopPropagation();
    mouseX = parseInt(e.clientX - offsetX);
    mouseY = parseInt(e.clientY - offsetY);
    drawLine(mouseX, mouseY);
}
canvas.onmouseup = function (e)  {
    if (!isDown) {
        return;
    }
    e.preventDefault();
    e.stopPropagation();
    isDown = false;
}