Создание графиков на Canvas - JS. Проблема с отрисовкой
Всем привет. Продолжаю экспериментировать с канвасом. Решил попробовать отрисовать графики, но столкнулся с небольшими изъянами графики.
Вот код (Можно нажать на W and S):
"use strict"
const c = document.getElementById("ctx");
const ctx = c.getContext("2d");
c.width = window.innerWidth;
c.height = window.innerHeight;
let size = 5;
function inRad(num) {
return num * Math.PI / 180;
}
function graph() {
ctx.fillStyle = "white";
ctx.fillRect(0, 0, c.width, c.height);
ctx.fillStyle = "black";
ctx.fillRect(0, c.height / 2, c.width, 1);
ctx.translate(c.width / 2, c.height / 2);
ctx.rotate(inRad(180));
ctx.fillStyle = "black";
ctx.fillRect(0, 0, 1, c.height);
ctx.beginPath();
ctx.moveTo(0, 0);
for (let i = -2000; i < 2000; i++) {
let x = i;
let y = Math.floor(Math.abs(i) ^ 2) * size;
ctx.lineTo(x, y);
}
ctx.stroke();
ctx.rotate(inRad(180));
ctx.translate(-c.width / 2, -c.height / 2);
}
graph();
window.addEventListener("keypress", (e) => {
console.log(e.keyCode)
if (e.keyCode === 119) {
size++;
} else if (e.keyCode === 115) {
size--;
}
graph();
})
<canvas id="ctx"></canvas>
Ответы (1 шт):
Автор решения: Victoria Tkachenko
→ Ссылка
Вам надо поменять знак возведения в степень во многих языках программирования возведение в степень ^, но в js **
for (let i = -2000; i < 2000; i++) {
let x = i;
let y = Math.floor(Math.abs(i) ** 2) * size; //Заменяем ^ на **
ctx.lineTo(x, y);
}
А ^, я сейчас посмотрела, складывает числа.