Skip to content

Instantly share code, notes, and snippets.

@diska
Created July 1, 2018 03:19
Show Gist options
  • Select an option

  • Save diska/00a626831538110edc9442840f343263 to your computer and use it in GitHub Desktop.

Select an option

Save diska/00a626831538110edc9442840f343263 to your computer and use it in GitHub Desktop.
WebGLで「WebGLFramebufferにデータを置いて、readPixelsする」サンプルコード。
<style>body{background-color:#9cc;}</style>
<style>textarea{background-color:#ffc;}</style>
<canvas id="CNVS" width="128" height="128"></canvas>
<textarea id="LOG" cols="32" rows="8"></textarea>
<h3>WebGL入門 06 WebGLFramebuffer</h3>
X<input id="X" type="range" max="7"><br/>
Y<input id="Y" type="range" max="7"><br/>
<script>
var cx=CNVS.getContext("webgl");cx.clearColor(0,.3,0,1);cx.clear(0x4000);
const map=16;
var dt0=new Uint8Array(map*map*4);
for(i=0;i<map*map*4;i++)dt0[i]=Math.random()*256;
var tex0=cx.createTexture();cx.bindTexture(cx.TEXTURE_2D, tex0);
cx.texImage2D(cx.TEXTURE_2D,0,cx.RGBA, map,map,0,cx.RGBA,cx.UNSIGNED_BYTE,dt0);
var fb0=cx.createFramebuffer();cx.bindFramebuffer(cx.FRAMEBUFFER, fb0);
cx.framebufferTexture2D(cx.FRAMEBUFFER,cx.COLOR_ATTACHMENT0,cx.TEXTURE_2D,tex0, 0);
var x=0,y=0, minimap=7;
var dt1=new Uint8Array(minimap*minimap*4);
function draw(now){
LOG.value =""; x=parseInt(X.value); y=parseInt(Y.value);
cx.readPixels(x,y,minimap,minimap, cx.RGBA, cx.UNSIGNED_BYTE,dt1);
for(p=0; p<minimap*minimap; p++){
var i=p*4;
if( 0<=dt1[i] && dt1[i]< 32)LOG.value+="森";
if( 32<=dt1[i] && dt1[i]<128)LOG.value+="・";
if(128<=dt1[i] && dt1[i]<192)LOG.value+="林";
if(192<=dt1[i] && dt1[i]<240)LOG.value+="へ";
if(240<=dt1[i] && dt1[i]<256)LOG.value+="町";
if(p%minimap==minimap-1)LOG.value+="\n";
}
LOG.value+=`(${x},${y})`;
requestAnimationFrame(draw);
} requestAnimationFrame(draw);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment