如何使HTML canvas的线条更平滑以绘制方程式

时间:2019-06-15 15:01:59

标签: html canvas

尝试制作绘图实用程序。我正在尝试使线条更平滑。我认为问题不在于如何在画布上绘制线条,而在于如何计算x和y坐标。

HTML

<canvas></canvas>

JS

const canvas = document.querySelector('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let c = canvas.getContext('2d');

// set the graph origin to middle of the canvas
const originX = window.innerWidth / 2;
const originY = window.innerHeight / 2;

c.strokeStyle = `rgba(240, 40, 40, 0.9)`;
c.beginPath();
c.moveTo(originX, originY);

// calculate x and y values for the equation "x^3"
for (let x = -60; x < 60; x = x + 0.1) {
  let y = x**3;
  draw(x, y);
}

function draw(x, y) {
  // Calculated the canvas specific coordinates
  let calculatedX = originX + x * 30;
  let calculatedY = originY + -y * 30;
  c.lineCap = "round";
  c.lineWidth = 1;
  // draw the line
  c.lineTo(calculatedX, calculatedY);
  c.stroke();
}

我尝试了解决其他线路平滑问题的方法,但是它们没有用。所以我认为问题出在for循环或draw function

在线站点:https://etasbasi.github.io/simple-grapher/dist/

0 个答案:

没有答案