Last active
February 16, 2021 04:27
-
-
Save diska/6fe2f90b79ab753e28ec057d722872c4 to your computer and use it in GitHub Desktop.
WebGL使うけどシェーダ使わずに3Dしてみるコード。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<canvas width="200" height="200"></canvas><hr/> | |
<script>"use strict"; | |
let VIEWPORT; | |
let opt={preserveDrawingBuffer:true}; | |
let cx=document.querySelector("canvas").getContext("webgl",opt); | |
viewport([0,0,cx.canvas.clientWidth,cx.canvas.clientHeight]); | |
let cube=[1,1,1, 1,-1,1], stride=3; | |
function draw(now){ | |
let time=now/1000; | |
cx.clearColor(0,.2,0,1);cx.disable(cx.SCISSOR_TEST);cx.clear(0x4000); | |
viewport([0,0,100,100]); draw2(time); | |
viewport([100,0,100,100]); draw2(time*4); | |
viewport([0,100,100,100]); draw2(-time*4); | |
viewport([100,100,100,100]); draw2(-time); | |
requestAnimationFrame(draw); | |
}; requestAnimationFrame(draw); | |
function draw2(time){ | |
for(let th=0; th<Math.PI*2; th+=Math.PI/2){ | |
let x,y,z; | |
for(let i=0;i<cube.length;i+=stride){ | |
[x,y,z]=[cube[i+0],cube[i+1],cube[i+2]]; | |
[x,y,z]=rotZ(x,y,z,th+time); | |
put(pers([x,y,z+4], 1/3),4) | |
} | |
} | |
} | |
function rotZ(x0,y0,z0,theta){ | |
const c=Math.cos(theta),s=Math.sin(theta); | |
return [x0*c-z0*s, y0, x0*s+z0*c]; | |
} | |
function pers([x0,y0,z0],f){ | |
let w=1+z0*f; | |
return [x0/w,y0/w]; | |
} | |
function viewport([ox,oy,w,h]=[0,0,cx.canvas.clientWidth,cx.canvas.clientHeight]){ | |
return VIEWPORT={ox:ox,oy:oy,w:w,h:h}; | |
} | |
function put([x0,y0],s=4){ | |
let [x,y]=[(x0+1)/2*VIEWPORT.w, (y0+1)/2*VIEWPORT.h]; | |
cx.scissor(VIEWPORT.ox+x,VIEWPORT.oy+y,s,s); cx.clearColor(1,1,1,1); | |
cx.enable(cx.SCISSOR_TEST); cx.clear(0x4000); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment