为什么Canvas不能绘制指数曲线?

3

我正在学校学习JavaScript的基础知识,现在正在学习canvas。

这是我的代码

canvas = document.getElementById("myCanvas")
ctx = canvas.getContext("2d")
offset = canvas.width / 2

function assi() {
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  ctx.beginPath()
  ctx.moveTo(offset, 0)
  ctx.lineTo(offset, offset * 2)
  ctx.moveTo(0, offset)
  ctx.lineTo(offset * 2, offset)
  ctx.stroke()
}

function f(x) {
  return Math.pow(2, x) * -1;
}

function draw() {
  assi()
  ctx.beginPath()
  ctx.strokeStyle = "red"

  moveTo(offset, f(0) + offset)
  for (let x = -offset; x < offset; x++) {
    ctx.lineTo(x + offset, f(x) + offset)
  }
  ctx.stroke()
}
<body onload="draw()">
  <canvas height="800" width="800" id="myCanvas"></canvas>
  <script src="script.js"></script>
</body>

这是我的问题
在函数f(x)中,如果我去掉*-1,它就不画出任何东西;而如果我删除*-1,它就会画出一些东西?

它可以绘制线性函数,但指数函数会有问题,而不是Math.pow() 的问题,因为如果我使用 1 作为底数,它可以工作(实际上会画出一条线,但是正确的)

需要使用*-1来将canvas坐标系(从上到下)镜像成笛卡尔坐标系(从下到上)的y轴。

1个回答

1

看起来绘制到非常负数的线条会导致问题...

如果你想让代码显示一些有用的东西,我们可以为那些具有正Y值的代码添加if语句,我们还可以限制到不是太大的负数,但这取决于你。
我正在绘制弧线以显示点,并将函数的输出分成较低的数量,以显示不同的曲线。

const canvas = document.getElementById("myCanvas")
const ctx = canvas.getContext("2d")
const offset = canvas.width / 2

function f(x) {
  return Math.pow(2, x) * -1;
}

let colors = ["black","cyan", "red", "blue", "green", "pink"]
for (let i = 1; i <= colors.length; i++) {
  ctx.beginPath()
  ctx.strokeStyle = colors[i-1]
  for (let x = -offset; x < offset; x++) {
    let y = f(x/i) + offset + i*10
    if (y > 0) {
      ctx.arc(x + offset, y, 1, 0, 6)
    }
  }
  ctx.stroke()
}
<canvas height="200" width="200" id="myCanvas"></canvas>

这是您的完整代码:

canvas = document.getElementById("myCanvas")
ctx = canvas.getContext("2d")
offset = canvas.width / 2

function assi() {
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  ctx.beginPath()
  ctx.moveTo(offset, 0)
  ctx.lineTo(offset, offset * 2)
  ctx.moveTo(0, offset)
  ctx.lineTo(offset * 2, offset)
  ctx.stroke()
}

function f(x) {
  return Math.pow(2, x) * -1;
}

function draw() {
  assi()
  ctx.beginPath()
  ctx.strokeStyle = "red"

  moveTo(offset, f(0) + offset)
  for (let x = -offset; x < offset; x++) {
    let y = f(x) + offset
    if (y > -1000) {
      ctx.lineTo(x + offset, y)
    }
  }
  ctx.stroke()
}
<body onload="draw()">
  <canvas height="200" width="200" id="myCanvas"></canvas>
</body>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接