wegl:transformations

check transformations

by bhupendra negi

HTML

<canvas id="mainCanvas">
    
</canvas>  
<div id = "div1">
<input id = "x" type="text" placeholder="enter x">
<input id = "y" type="text" placeholder="enter y">
<button onclick="dotransform()">Translation</button>
 </div>    
<div id = "div2">    
<input id = "angle" type="text" placeholder="angle" value=10>   
<button onclick="dorotate()">Rotate</button> 
 <button onclick="dotimer()">Timer</button>    
 <div>  
<div id = "div4">
 <input id = "sx" type="text" placeholder="scale x">
<input id = "sy" type="text" placeholder="scale y">
<button onclick="doscale()">Scale</button>
  </div>   
     
 <div id = "div3">
 
<button onclick="doreset()">Reset</button>       
   
  </div>

CSS

canvas {
    width:400;
    height:400;
    display:block;
}
input {
    width:50px;
    margin:5px;
    
}

JavaScript

//function for transform
 var vertices,gl,buffer,shaderProgram;


function dotimer()
{ dorotate();
 requestAnimationFrame(dotimer); 
    
}


function doreset()
{
    
 var elements = document.getElementsByTagName("input");
for (var ii=0; ii < elements.length; ii++) {
  if (elements[ii].type == "text") {
    elements[ii].value = "";
  }
}   
 main();   
}

function doscale()
{
// creating new vertices   
 var dx= parseFloat(document.getElementById("sx").value);
 var dy= parseFloat(document.getElementById("sy").value);
    
for(i=0;i<6;i+=2)
{
  vertices[i]*=dx;
  vertices[i+1]*=dy;
   
}   
 
 main("transform",vertices)   
 
    
}

function dotransform()
{
 // creating new vertices   
 var dx= parseFloat(document.getElementById("x").value);
 var dy= parseFloat(document.getElementById("y").value);
    
for(i=0;i<6;i+=2)
{
  vertices[i]+=dx;
  vertices[i+1]+=dy;
   
}   
 
 main("transform",vertices)   
    
}

// function for rotation

function dorotate()
{
    console.log("rotate");
 var deg = parseFloat(document.getElementById("angle").value);
//     console.log("rotate "+deg);
    
 var radian = Math.PI * (deg/180.0);   
 
for(i=0;i<6;i+=2)
{
  var ox = vertices[i];
  var oy = vertices[i+1];  
  var newv[];
    
  newv[i] =ox +ox*Math.cos(radian) - oy*Math.sin(radian);
  newv[i+1] = oy +ox*Math.sin(radian) + oy*Math.cos(radian);
   
}  
    console.log(newv);
 main("rotate",newv)  ;
    
    
    
    
}



function main(type,newvertices)
{
   // Configure the canvas to use WebGL
   //
  
   var canvas = document.getElementById('mainCanvas');
   try {
      gl = canvas.getContext('experimental-webgl');
   } catch (e) {
      throw new Error('no WebGL found');
   }

   // Copy an array of data points forming a triangle to the
   // graphics hardware
   //
     vertices = [
       0.0, 0.0,
      -0.5,  0.5,
     -0.5, -0.5
             
   ];

   buffer = gl.createBuffer();
   gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
    if (type!= null)
  ...