So i have an animation where the small colorful small circles are growing.
I wish to access the RGB value of the point where my mouse clicks.
I tried two ways to present the x,y. one is in [-1,1]. The other way is the original values. But none of them worked.
I skipped some codes in the main function as they are not relevant to the click function.
var VSHADER_SOURCE =
'attribute vec4 a_Position;\n' +
'uniform float u_SizeChange;\n' +
'void main() {\n' +
' gl_Position.x = u_SizeChange * a_Position.x;\n' +
' gl_Position.y = u_SizeChange * a_Position.y;\n' +
' gl_Position.z = u_SizeChange * a_Position.z;\n' +
' gl_Position.w = 1.0;\n' +
'}\n';
var FSHADER_SOURCE =
'precision mediump float;\n' +
'uniform vec4 u_FragColor;\n' +
'void main() {\n' +
' gl_FragColor = u_FragColor;\n' +
'}\n';
function main() {
var canvas = document.getElementById('webgl');
// Get the rendering context for WebGL
var gl = getWebGLContext(canvas);
if (!gl) {
console.log('Failed to get the rendering context for WebGL');
return;
}
// Initialize shaders
if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
console.log('Failed to intialize shaders.');
return;
}
var tick = function() {
canvas.onmousedown = function(ev){click(ev,canvas,random_location,gl);};
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);
draw_circle(gl, 0, 0, disk_radius/400,[1.0,1.0,1.0,1.0]);
if (game_running==true){requestAnimationFrame(tick, canvas);}
};
tick();
} }
function click(ev,canvas,random_location,gl) {
var x = ev.clientX; // x coordinate of a mouse pointer
var y = ev.clientY; // y coordinate of a mouse pointer
var rect = ev.target.getBoundingClientRect() ;
x = ((x - rect.left) - canvas.width/2)/(canvas.width/2);
y = (canvas.height/2 - (y - rect.top))/(canvas.height/2);
var x = ev.clientX - canvas.offsetLeft;
var y = ev.clientY - canvas.offsetTop;
const pixel = new Uint8Array(4);
gl.readPixels(x, y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
console.log(x,y);
console.log(pixel);
for (var i=0; i<=random_location.length;i++){
// bacteria_alive[i]=false;
if (bacteria_alive[i]==false){continue;}
distance_to_center = cal_distance(x,y,0+disk_radius*Math.sin(random_location[i])/400,0+disk_radius*Math.cos(random_location[i])/400);
if (distance_to_center < radius/400){
bacteria_alive[i]=false;
break;
}
}
}