Tag Archives: WebGL

A simple sphere with Three.js .

This tutorial is about how to add a simple wireframe sphere into your webpage using the a javascript 3D library named three.js .
This 3D library and some demo and examples can be found here.
The tutorial for today is let you to know how to deal with a simple object.
First you need to make a folder named project.
Into this folder create two folder named js and css.
Into the project create a index.html file and add this content:

Make a file named style.css into css folder and add this:

This wi
Into js folder create a file named index.js and add this source code:

This java script file follow some steps to make the wireframe sphere:

  • make the scene;
  • set the camera;
  • create the renderer space;
  • add the renderer space to HTML document;
  • create sphere
  • add one material ;
  • make a wireframe from geometry variable;
  • create wireframe object;
  • create a line like wireframe object;
  • deal with line material;
  • add line to the scene;
  • set the position of camera;
  • create the render function to animate the content;
  • run all with render function.

The result is something like this:

Some changes can be used into this example to see how is working.
You can remove the css folder and style file but you need to remove this line from index.html file:

The sphere variable can be added into java script source code:

This will make some change into the render canvas.

Posted in All, HTML 5, javascript, Programming, web, WebGL. Tagged with , , , , , , .

Mandelbrot with three.js .

The Mandelbrot set is the set of complex numbers c for which the function f c ( z ) = z 2 + c {\displaystyle f_{c}(z)=z^{2}+c} {\displaystyle f_{c}(z)=z^{2}+c} does not diverge when iterated from z = 0 {\displaystyle z=0} z=0, i.e., for which the sequence f c ( 0 ) {\displaystyle f_{c}(0)} {\displaystyle f_{c}(0)}, f c ( f c ( 0 ) ) {\displaystyle f_{c}(f_{c}(0))} {\displaystyle f_{c}(f_{c}(0))}, etc., remains bounded in absolute value.wikipedia.org

You need to download the three.js – java script from threejs webpage.
The source code is simple. Come with default HTML5 page and javascripts.
One part of this will make vertex-shader and fragment shader, both is 2D shader type.
You need the canvas tag with id=”canv”.
The last part of source code is make to put all into one image processing by shaders.

Posted in All, HTML 5, javascript, Programming, WebGL, Windows 10. Tagged with , , , , , , , , .

Shader x-ray effect with Three.js .

This source code running with Three.js javascript library.

I used just three.min.js, OBJLoader.js and ColladaLoader.js to make the x-ray effect.

I load one 3d object and using vertex and fragment shaders I rendered it.

The object is a castle and is named: cube2.dae.

This object is loaded with load function from OBJLoader.js.

Then all steps come to show this object using shaders.

<!DOCTYPE html>
<html>

<head>
<title>shaders x-ray effect</title>
<script src=”three.min.js”></script>
<script src=”OBJLoader.js”></script>
<script src=”ColladaLoader.js”></script>

<script id=”vertexShader” type=”x-shader/x-vertex”>
uniform float p;
varying float intensity;
void main()
{
vec3 vNormal = normalize( normalMatrix * normal );
intensity = pow(1.0 – abs(dot(vNormal, vec3(0, 0, 1))), p);
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}
</script>

<script id=”fragmentShader” type=”x-shader/x-vertex”>
uniform vec3 glowColor;
varying float intensity;
void main()
{
vec3 glow = glowColor * intensity;
gl_FragColor = vec4( glow, 1.0 );
}
</script>
<style>
html, body {
height: 100%;
margin: 0;
overflow: hidden;
}
canvas {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<script>
window.addEventListener(‘load’, function () {
var human;

var $ = document.querySelector.bind(document);

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(45, 1, 0.1, 30);
var renderer = new THREE.WebGLRenderer({antialias: true, alpha: true});

renderer.setClearColor(0x000000, 1.0);

lookAt = scene.position;
lookAt.y = 10;
camera.lookAt(lookAt);

document.body.appendChild(renderer.domElement);

var customMaterial = new THREE.ShaderMaterial({
uniforms: {
p: { type: “f”, value: 3 },
glowColor: { type: “c”, value: new THREE.Color(0x84ccff) },
},
vertexShader: $(‘#vertexShader’).text,
fragmentShader: $(‘#fragmentShader’).text,
side: THREE.DoubleSide,
blending: THREE.AdditiveBlending,
transparent: true,
depthWrite: false
});

var loader = new THREE.ColladaLoader();
loader.options.convertUpAxis = true;
loader.load(‘cube2.dae’, function (collada) {
dae = collada.scene;

dae.traverse( function ( child ) {

if (child instanceof THREE.Mesh) {
child.material = customMaterial;
}

} );

dae.position.y = 0;
dae.scale.x = 1;
dae.scale.y = 1;
dae.scale.z = 1;
human = dae;
scene.add(human);
});

function resize() {
var canvas = renderer.domElement;
var width  = canvas.clientWidth;
var height = canvas.clientHeight;
if (canvas.width !== width || canvas.height !== height) {
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
}

function render(time) {
time *= 0.001;

resize();

camera.position.x = -20 * (Math.cos(time));
camera.position.z = (20 * (Math.sin(time)));
camera.position.y = 20;

camera.lookAt(lookAt);

renderer.render(scene, camera);
requestAnimationFrame(render);
}
requestAnimationFrame(render);

});
</script>
</body>

</html>

The result is this:
x-ray_effect

Posted in All, HTML 5, javascript, Programming, web, WebGL. Tagged with , , , , , , .

WebGL – sound visualizer with Three.js .

First you need to create one html5 default webpage.
Also you need to add the three.js library to your file.
Add your MP3 file to your folder project.
I named my mp3 file with your_sound_file.mp3.
Because you used three.js javascript file you need to have this functions:init, animate, onError.
To used the audio file you need to have this functions: Play and Load.
The visualizer is make with NewLine function.
This function make one material with one line with green color: 0x00ff00.
If you take a look to the source code will see is simple.
… and result is this:
sounds
see the source code:
<!doctype html>
<html>
<head>
<script src=”js/three.min.js”></script>
</head>
<body>
<script>

var scene, camera, renderer, line;
var geometry, material, mesh, array;

function init() {

scene = new THREE.Scene();

camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.z = 1000;

renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );

document.body.appendChild( renderer.domElement );

}

function NewLine() {

scene.remove(line);

var material = new THREE.LineBasicMaterial({
color: 0x00ff00
});

var geometry = new THREE.Geometry();

array = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(array)

var Ypoints = array;
var xPoint = -2048;
for(var i=0;i<Ypoints.length;i++) {
geometry.vertices.push( new THREE.Vector3( xPoint, Ypoints[i], 0 ) );
xPoint = xPoint + 4;
}

line = new THREE.Line( geometry, material );
scene.add( line );
}

function animate() {

requestAnimationFrame( animate );
NewLine();
renderer.render( scene, camera );

}

window.AudioContext = window.AudioContext || window.webkitAudioContext;
var context = new AudioContext();

function Play(buffer) {
var source = context.createBufferSource();
source.buffer = buffer;
source.connect(context.destination);

analyser = context.createAnalyser();
source.connect(analyser);
analyser.connect(context.destination);

source.start(0);

init();
animate();
}

function Load(url) {
var request = new XMLHttpRequest();
request.open(‘GET’, url, true);
request.responseType = ‘arraybuffer’;

request.onload = function() {
context.decodeAudioData(request.response, function(buffer) {
Play(buffer)

}, onError);
}
request.send();

function onError() {
console.log(‘error’)
}
}
Load(‘your_sound_file.mp3’);
</script>
</body>
</html>

Posted in All, HTML 5, javascript, Programming, web, WebGL. Tagged with , , , , , , .

WebGL – simple shader example.

This is a simple webgl shader example.
I used a simple HTML5 example with one canvas.
The canvas has named glscreen. The next step is to put one java script with one var named buffer.
The buffer var is used for one array. The Float32Array typed array represents an array of 32-bit floating point numbers.
This var come with this source code into init function.

buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(
gl.ARRAY_BUFFER,
new Float32Array([
-1.0, -1.0,
1.0, -1.0,
-1.0,  1.0,
-1.0,  1.0,
1.0, -1.0,
1.0,  1.0]),
gl.STATIC_DRAW
);
We can see also we have two functions: init and render and this:

var gl;
var canvas;
var buffer;

window.onload = init;
I put also two default shaders for vertex and fragment.
I use some vars for this into init function:

var shaderScript;
var shaderSource;
var vertexShader;
var fragmentShader;

This is the script:

<!DOCTYPE html>
<head>
<title>WebGL – Hello World!</title>
</head>
<body>
<script type=”text/javascript”>
var gl;
var canvas;
var buffer;

window.onload = init;

function init() {
var shaderScript;
var shaderSource;
var vertexShader;
var fragmentShader;

canvas        = document.getElementById(‘glscreen’);
gl            = canvas.getContext(‘experimental-webgl’);
canvas.width  = 640;
canvas.height = 480;

gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(
gl.ARRAY_BUFFER,
new Float32Array([
-1.0, -1.0,
1.0, -1.0,
-1.0,  1.0,
-1.0,  1.0,
1.0, -1.0,
1.0,  1.0]),
gl.STATIC_DRAW
);

render();

}

function render() {

window.requestAnimationFrame(render, canvas);

shaderScript = document.getElementById(“2d-vertex-shader”);
shaderSource = shaderScript.text;
vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, shaderSource);
gl.compileShader(vertexShader);

shaderScript   = document.getElementById(“2d-fragment-shader”);
shaderSource   = shaderScript.text;
fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, shaderSource);
gl.compileShader(fragmentShader);

program = gl.createProgram();
gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);
gl.linkProgram(program);
gl.useProgram(program);
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);

positionLocation = gl.getAttribLocation(program, “local_position”);
gl.enableVertexAttribArray(positionLocation);
gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
gl.drawArrays(gl.TRIANGLES, 0, 6);
}
</script>
<script id=”2d-vertex-shader” type=”x-shader/x-vertex”>
attribute vec2 local_position;
void main() {
gl_Position = vec4(local_position, 0, 1);
}
</script>
<script id=”2d-fragment-shader” type=”x-shader/x-fragment”>
void main() {
gl_FragColor = vec4(gl_FragCoord.x / 640.0, gl_FragCoord.y / 480.0, 0, 1);
}
</script>
<canvas id=”glscreen”></canvas>
</body>
</html>
The result is this:

shader001

Posted in 3D, All, HTML 5, javascript, Programming, WebGL. Tagged with , , , , .