Skip to content

Instantly share code, notes, and snippets.

@diska
Last active February 11, 2021 08:24
Show Gist options
  • Select an option

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

Select an option

Save diska/ba17be414c8fd1c59a5ffbb857a6ab49 to your computer and use it in GitHub Desktop.
マウス座標の扱いってこんな簡単だったっけ?という、WebGLでお絵かきなコード。
<canvas width="256" height="256"></canvas><hr/>
<input type="text">
<script>"use strict";
let vsrc=`uniform vec2 m;varying vec2 vm;
void main(){vm=m;gl_PointSize=4.;gl_Position=vec4(m,0,1);}`;
let fsrc=`precision highp float;varying vec2 vm;
void main(){gl_FragColor=vec4(vm/2.+1.,0,1);}`;
let opt={preserveDrawingBuffer:true};
let cx=document.querySelector("canvas").getContext("webgl",opt);
let LG=document.querySelector("input");
let pg=cx.createProgram();
let vs=cx.createShader(cx.VERTEX_SHADER);cx.attachShader(pg,vs);
let fs=cx.createShader(cx.FRAGMENT_SHADER);cx.attachShader(pg,fs);
cx.shaderSource(vs,vsrc);cx.compileShader(vs);
cx.shaderSource(fs,fsrc);cx.compileShader(fs);cx.linkProgram(pg);
cx.useProgram(pg);
let pgM=cx.getUniformLocation(pg,"m");
cx.clearColor(.3,.3,.3,1); cx.clear(0x4000);
let m=new Float32Array(2), sw=false;
let draw=(now)=>{
cx.uniform2fv(pgM,m); if(sw)cx.drawArrays(0,0,1);
requestAnimationFrame(draw);
}; requestAnimationFrame(draw);
let move=(e)=>{m=[e.offsetX/128-1,-1*(e.offsetY/128-1)];LG.value=`${sw},${m}`;}
cx.canvas.addEventListener("mousemove",move);
cx.canvas.addEventListener("mousedown",e=>sw=true);
cx.canvas.addEventListener("mouseup",e=>sw=false);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment