如何使用鼠标悬停在HTML画布上折线

时间:2018-12-22 23:16:04

标签: javascript canvas vector-graphics

以下代码在HTML canvas元素上绘制了一行网格:

当鼠标悬停在线条附近时,是否可以弯曲/扭曲线条?

var canvas = document.getElementById('grid');
var context = canvas.getContext("2d");
var ww = innerWidth; // Window Width
var wh = innerHeight; // Window Height

canvas.width = ww;
canvas.height = wh;

function drawLines() {
    for(var i = 0; i < ww; i += 30) {
        context.moveTo(i , 0);
        context.lineTo(i , wh);
    }

    for(var i = 0; i < wh; i += 30) {
        context.moveTo(0, i);
        context.lineTo(ww, i);
    }

    context.lineWidth = 1;
    context.strokeStyle = "#333";
    context.stroke();
}

drawLines();
canvas { width: 100%; height: 100% }
<canvas id="grid"></canvas>

1 个答案:

答案 0 :(得分:0)

您必须将所有x, y网格值存储在2d数组中,然后适当地呈现它们。

并为所有points添加某种物理行为 verlet physics会很好,或者spring physics

伪代码

        for (let i = 0; i < height; i++) {
            for (let j = 0; j < width; j++) {
                points.push([
                    x,y,
                ])
                x += gap;
            }
            y += gap;
        }