javascript - 如何在用户定义的行中创建行

标签 javascript canvas

我有这个代码:

sample.beginPath();
sample.moveTo(X1.x,Y1.x );
sample.lineTo(X2.x,Y2.y);
sample.stroke();

sample.beginPath();
sample.arc(X1.x, Y1.y, 4, 0, 2 * Math.PI, false);
sample.fill();
sample.lineWidth = 1;
sample.stroke();

sample.beginPath();
sample.arc(X2.x, Y2.y, 4, 0, 2 * Math.PI, false);
sample.fill();
sample.lineWidth = 1;
sample.stroke();

这将创建这个:

enter image description here

我想要的是:

enter image description here

请假设它是直线并且圆圈被正确绘制。

注意:在无穷远的直线上,直线仍然是连通的

最佳答案

基本上,您的代码只需要在两个循环中运行 - 一个在向前方向绘制线段的副本,另一个在向后方向绘制线段的副本。

这个修改后的版本通过向前和向后绘制来绘制一条无限线,直到它碰到 Canvas 的边缘。

这是实际输出的截图:

screenshot

这是最终工作解决方案的现场演示:

var canvas = document.getElementById("thecanvas");
var sample = canvas.getContext("2d");

function drawLine(x1, y1, x2, y2) {
    sample.strokeStyle = '#000000';
    
    sample.beginPath();
    sample.moveTo(x1, y1);
    sample.lineTo(x2, y2);
    sample.lineWidth = 2;
    sample.stroke();

    sample.beginPath();
    sample.arc(x1, y1, 4, 0, 2 * Math.PI, false);
    sample.fillStyle = "#FFFFFF";
    sample.fill();
    sample.lineWidth = 1;
    sample.stroke();
}

function drawInfLine(x1, y1, x2, y2) {
    var xstep = x2 - x1;
    var ystep = y2 - y1;
    
    var lastx = x1;
    var lasty = x2;
    var currx;
    var curry; // yum
    
    // Draw forwards
    while (lastx <= canvas.width && lasty <= canvas.height) {
        currx = lastx + xstep;
        curry = lasty + ystep;
        drawLine(lastx, lasty, currx, curry);
        lastx = currx;
        lasty = curry;
    }
    
    // Reset initial drawing point
    lastx = x1;
    lasty = x2;
    
    // Draw backwards
    while (lastx >= 0 && lasty >= 0) {
        currx = lastx - xstep;
        curry = lasty - ystep;
        drawLine(lastx, lasty, currx, curry);
        lastx = currx;
        lasty = curry;
    }
}

drawInfLine(50, 0, 110, 5);
<canvas id="thecanvas" width="400" height="200"></canvas>

JSFiddle 版本:https://jsfiddle.net/k83153br/2/

关于javascript - 如何在用户定义的行中创建行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32773271/

相关文章:

javascript - 使用 Canvas 在矩形内绘制矩形?

php - jQuery 发布到 PHP 进行重定向?

javascript - 有没有办法在 Canvas 路径上平铺背景图像?

delphi - 如何绘制 Unicode 文本?

javascript - 如何使用 getContext ('webgl' 在 Canvas 上复制另一个 Canvas 的数据)?

twitter-bootstrap - 如何使用 Bootstrap 在 Paper.js 中设置 Canvas 的 view.viewSize

javascript - 如何使用 Javascript 键事件重命名选项卡?

javascript - 需要解决这个 javascript 编码问题

javascript - 使用 javascript 创建随机 sha1 盐

javascript - 在图像上画一条线