gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:38:39 24 4
gpt4 key购买 nike

我有这个代码:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com