Skip to content

Instantly share code, notes, and snippets.

@h4k1m0u
Created June 18, 2022 23:06
Show Gist options
  • Save h4k1m0u/4a4e2de076629d4eccbe192475f94e7b to your computer and use it in GitHub Desktop.
Save h4k1m0u/4a4e2de076629d4eccbe192475f94e7b to your computer and use it in GitHub Desktop.
Draw a noisy triangle with WebGL using Regl and Glslify
// file: src/index.js
const glsl = require('glslify')
const regl = require('regl')();
/* Tutorial: https://vallandingham.me/regl_intro.html */
const drawTriangle = regl({
vert: glsl.file('./shaders/noise.vert'),
frag: glsl.file('./shaders/noise.frag'),
attributes: {
position: [[0, -1], [-1, 0], [1, 1]],
},
count: 3,
});
drawTriangle();
// file: src/shaders/noise.frag
// fragment shaders don't have a default precision
precision mediump float;
// import perlin noise function
#pragma glslify: noise = require(glsl-noise/simplex/2d)
void main() {
// gl_FragCoord gives pixel coords rel. to origin = lower-left corner of window,
// pixel center at half-pixel center => origin = (0.5, 0.5)
float brightness = noise(gl_FragCoord.xy);
gl_FragColor = vec4(brightness, 0, 0, 1);
}
// file: src/shaders/noise.vert
attribute vec2 position;
void main() {
gl_Position = vec4(position, 0, 1);
}
{
"name": "webgl-example",
"version": "1.0.0",
"description": "",
"main": "src/index.js",
"scripts": {
"start": "budo src/index.js --live"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"glsl-noise": "*",
"glslify": "^7.1.1",
"regl": "^2.1.0"
},
"devDependencies": {
"budo": "^11.7.0"
},
"browserify": {
"transform": [ "glslify" ]
}
}

Install dependencies

$ npm install

Run on webbrowser

$ npm start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment