我正在尝试使用 lineTo(( 方法在 html5 中绘制一条双曲线。我有以下代码:
$(function () {
var context = document.getElementById("myCanvas").getContext("2d");
context.moveTo(0,198);
iteration = 0.21
for(var x = 0 + iteration; x <= 500; x += iteration) {
context.lineTo(x, 500/(x-250)+200);
}
context.stroke();
});
这非常有效,但是如果我将迭代更改为 0.2 或更低,图形不会出现在屏幕上。
观看演示: http://jsfiddle.net/1kjpjryr/
有人知道为什么图形在特定值 0.2 处失败吗?
谢谢一月
问题是当 x === 250 时,你正在用无穷大破坏路径。
在Javascript中,一个数字除以零等于无穷大。除了 2D 上下文不接受无穷大作为有效坐标这一事实之外,一切都很好,因此自 ctx.beginPath()
年以来认为整个路径都是无效的。
因为iteration = 0.21
从不让x === 250
它不会导致问题,但是有了iteration = 0.2
,您将对iteration = 0.5
或1
或0.1
或许多其他人x === 250
相同。事实上,函数的正值或负值的适当大值都会破坏路径,而不仅仅是无穷大。
您需要确保表达式 f(x) = 500/(x-250)+200
给出的坐标不超过 2D 上下文可以处理的最大值或最小值。(我不知道数字是多少,但超出您渲染范围的任何内容都是可以接受的。
以下内容将修复您的函数
var lineStart = true; // semaphore to indicate start of a new line
var iteration = 0.2;
var graphMax = 10000; // |y| the positive max value that should be rendered.
for (var x = 0 + iteration; x <= 500; x += iteration) {
if (Math.abs(500 / (x - 250)) > graphMax) {
// skip the point
lineStart = true;
} else {
if (lineStart) { // is this the start of a line
lineStart = false; // yes so move to and clear semaphore
context.moveTo(x, 500 / (x - 250) + 200);
} else {
context.lineTo(x, 500 / (x - 250) + 200);
}
}
}