Function graph in JavaScript


You need to use JavaScript to plot the function y = х^2 + (е^2x)/(х-2) where e is the exponent (in power 2*x), x = -5 and in increments of 0.1 (i.e. -5 + 0.1) to 10 (you can also go up to 1). I ask for help, or at least a link to a resource that explains how this can be done. Thanks for your attention.

Author: Stranger in the Q, 2019-05-06

2 answers

Here you have y = x^2 on the interval [-2,2]

enter a description of the image here

let y = x => x*x; // функция
let z = 40; // масштаб
let c = document.querySelector('canvas');
let ctx = c.getContext('2d');

// центровочка
ctx.translate(c.width/2, c.height/2)
   
// сетка
ctx.beginPath();
for (let x = -3; x <3; x++) {
  ctx.moveTo(x*z, -c.height/2);
  ctx.lineTo(x*z, c.height/2);
  ctx.moveTo(-c.width/2, x*z);
  ctx.lineTo(c.width/2, x*z);
}
ctx.stroke();

// график функции
ctx.strokeStyle = "red";
ctx.lineWidth = 3;
ctx.beginPath();
for (var i = -2; i <= 2; i += 0.2) {
  ctx[i?'lineTo':'moveTo'](i*z, -y(i)*z);
}
ctx.stroke();
<canvas width=175 height=175></canvas>
 9
Author: Stranger in the Q, 2019-05-06 12:05:56

Here is a variant using svg, draw superformula.

In the polar coordinate system, the superformula looks like this:

enter a description of the image here, where r radius, a - angle

Here are the figures obtained if you substitute various coefficients in this formula, (see the snippet for details):

enter a description of the image here

function superformula(phi, r, m1, m2, n1, a, b, n2, n3) {
    with (Math) {
        // считаем значение значение суперформулы для угла phi
        let d = pow( pow(abs(cos(m1*phi/4))/a, n2) + 
                     pow(abs(sin(m2*phi/4))/b, n3), -1/n1) * r; 
        // переводим в декартову систему координат       
        return `${(d*cos(phi))},${(d*sin(phi))}`; 
    }
}

// считаем n значений для углов в диапазоне [0, 2*PI] через равные промежутки
// и собираем все значение в команды пути для svg path
function pathD(n, params) {
    return `M${Array(n).fill(0).map((e, i) => superformula(i/n*Math.PI*2, ...params))}Z`;
}

document.querySelectorAll('path[superformula]').forEach(path => {
    path.setAttribute('d', pathD(200, path.getAttribute('superformula').split(',')))
})
body {
  margin:0;
  overflow: hidden;
}

svg {
  display: inline-block;
  height: 90vh;
  margin-left: -25px;
}

path {
  fill: none;
  stroke: red;
  stroke-width: 2px;
}
<svg viewbox="0 0 650 190">
    <path transform="translate(100,100)" superformula="30,5,5,2,1,1,7,7"/>
    <path transform="translate(200,100)" superformula="30,8,8,2,1,0.6,5,8"/>
    <path transform="translate(300,100)" superformula="30,4,4,2,1,2,5,2"/>
    <path transform="translate(400,100)" superformula="30,4,4,1,1,2,1,1"/>
    <path transform="translate(500,100)" superformula="30,12,12,0.3,1,1,0,10"/>
    <path transform="translate(600,100)" superformula="30,5,5,1000,1,1,600,600"/>
</svg>
 5
Author: Stranger in the Q, 2019-05-08 08:36:25