Getting Started
Prepare HTML
Create an HTML canvas with an appropriate width or height:
<div>
<canvas style="width: 100%;" id="my_canvas"></canvas>
</div>
Import JS module
Import WebGL-Plot library using ES6 modules:
import WebGLplot, { WebglLine, ColorRGBA } from "webgl-plot";
Prepare the canvas
const canvas = document.getElementById("my_canvas");
const devicePixelRatio = window.devicePixelRatio || 1;
canvas.width = canvas.clientWidth * devicePixelRatio;
canvas.height = canvas.clientHeight * devicePixelRatio;
Initialization:
const wglp = new WebGLplot(canvas);
Add a line
create a line
const color = new ColorRGBA(Math.random(), Math.random(), Math.random(), 1);
const line = new WebglLine(color, canv.height);
gnereate the x data points
line.lineSpaceX(-1, 2 / numX);
Add the line to webgl canvas:
wglp.addLine(line);
Dynamic update
Configure the requestAnimationFrame call:
function newFrame() {
update();
wglp.update();
requestAnimationFrame(newFrame);
}
requestAnimationFrame(newFrame);
Add an update function:
function update() {
const freq = 0.001;
const amp = 0.5;
const noise = 0.1;
for (let i = 0; i < line.numPoints; i++) {
const ySin = Math.sin(Math.PI * i * freq * Math.PI * 2);
const yNoise = Math.random() - 0.5;
line.setY(i, ySin * amp + yNoise * noise);
}
}