按向左或向右按​​钮更改颜色时遇到问题 [英] Having trouble changing color by pressing left or right button

查看:119
本文介绍了按向左或向右按​​钮更改颜色时遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法更改,当您从左到右按钮时更改颜色。按住鼠标左键并将其移动到画布中应该绘制鼠标在红色圆点和蓝色圆点的运动轨迹,当您按住鼠标右键时。



问题是:一旦你用左键点击,右键改变左键绘制的颜色,反之亦然。



需要帮助或提示如何解决这个问题。谢谢。



javascript:

  //顶点着色程序
var VSHADER_SOURCE =
'attribute vec4 a_Position; \\\
'+
'void main(){\\\
'+
'gl_Position = a_Position; \\\
'+
'gl_PointSize = 10.0; \\\
'+
'} \\\
';

//片段着色程序
var FSHADER_SOURCE =
'precision mediump float; \\\
'+
'uniform vec4 u_FragColor; \\\
'+
'void main(){\\\
'+
'gl_FragColor = u_FragColor; \\\
'+
'} \\\
'

var mousePressed = false; //如果鼠标按下则保持boolean
var leftClick = false; //保持boolean如果按下鼠标左键
var rightClick = false; //保存boolean如果按下右键

function main()
{
// Retrieve< canvas> element
var canvas = document.getElementById('webgl');

//获取WebGL的渲染上下文
var gl = getWebGLContext(canvas);
if(!gl)
{
console.log('无法获取WebGL的渲染上下文');

return;
}

//初始化着色器
if(!initShaders(gl,VSHADER_SOURCE,FSHADER_SOURCE))
{
console.log('着色器。
return;
}

//获取a_Position的存储位置
var a_Position = gl.getAttribLocation(gl.program,'a_Position');
if(a_Position< 0)
{
console.log('无法获取a_Position的存储位置');
return;
}

//获取u_FragColor的存储位置
var u_FragColor = gl.getUniformLocation(gl.program,'u_FragColor');
if(!u_FragColor)
{
console.log('无法获取u_FragColor的存储位置');
return;
}

//注册函数(事件处理程序)要在鼠标mousePressed上调用
canvas.onmousedown = function(ev)
{
console .log('f1 called');
//确定正在按下的是哪个单击
switch(ev.which)
{
case 1:// leftClick click
leftClick = true;
break;
case 3:// rightClick点击
rightClick = true;
break;
}

//鼠标点击被按下
mousePressed = true;

//调用函数
//console.log('calling f1');
// drawDots(ev,gl,canvas,a_Position,u_FragColor,false);
// drawDots(ev,gl,a_Position,u_FragColor,false);
};

canvas.onmousemove = function(ev)
{
console.log('f2 called');
if(mousePressed)
{
console.log('calling drawDots');
drawDots(ev,gl,canvas,a_Position,u_FragColor,true);
}
// drawDots(ev,gl,a_Position,u_FragColor,true);
};

canvas.onmouseup = function(ev)
{
console.log('f3 called');
mousePressed = false;
leftClick = false;
rightClick = false;
};

//指定清除< canvas>的颜色
gl.clearColor(0.0,0.0,0.0,1.0);
console.log('clearColor call');

//清除< canvas>
gl.clear(gl.COLOR_BUFFER_BIT);
console.log('clear call');
}

var g_points = []; //用于鼠标位置的数组$ p

函数drawDots(ev,gl,canvas,a_Position,u_FragColor,down)
// function drawDots(ev,gl,a_Position,u_FragColor ,down)
{
console.log('drawDots called');
var rect = ev.target.getBoundingClientRect();

var x = ev.clientX; //鼠标指针的x坐标
var y = ev.clientY; //鼠标指针的y坐标

x =((x-rect.left) - canvas.width / 2)/(canvas.width / 2);
y =(canvas.height / 2 - (y-rect.top))/(canvas.height / 2);

//左键单击
if(down == true&& leftClick == true)
{
console.log('left') ;
//将坐标存储到g_points数组
g_points.push(x); g_points.push(y);

//清除< canvas>
gl.clear(gl.COLOR_BUFFER_BIT);

var len = g_points.length;

for(var i = 0; i< len; i + = 2)
{
//将点的位置传递给a_Position变量
gl .uniform4f(u_FragColor,1.0,0.0,0.0,1.0);
gl.vertexAttrib3f(a_Position,g_points [i],g_points [i + 1],0.0);


//绘制
gl.drawArrays(gl.POINTS,0,1);
}
}
//右键单击
else if(down == true&& rightClick == true)
{
console.log ('right right');
//将坐标存储到g_points数组
g_points.push(x); g_points.push(y);

//清除< canvas>
gl.clear(gl.COLOR_BUFFER_BIT);

var len = g_points.length;
for(var i = 0; i< len; i + = 2)
{
//将点的位置传递给a_Position变量
gl.uniform4f(u_FragColor ,0.0,0.0,1.0,1.0);
gl.vertexAttrib3f(a_Position,g_points [i],g_points [i + 1],0.0);


//绘制
gl.drawArrays(gl.POINTS,0,1);
}
}
}


解决方案>

对于添加到 g_points 的每个点,您需要记住该点创建的颜色。因此,您可以创建另一个数组来跟踪点颜色。

  var g_points = []; //鼠标位置的数组压缩
var g_colors = [];

每次添加点时,将颜色添加到数组。

  //将坐标存储到g_points数组
g_points.push(x); g_points.push(y);

//存储颜色
g_colors.push([1.0,0.0,0.0,1.0]);

然后更新for循环以使用每个点的给定颜色。

  for(var i = 0; i  {
//指向a_Position变量
gl.uniform4fv(u_FragColor,g_colors [i / 2]);
gl.vertexAttrib3f(a_Position,g_points [i],g_points [i + 1],0.0);


//绘制
gl.drawArrays(gl.POINTS,0,1);
}

请务必同时更新左点击代码和右键点击代码,使用颜色。



这是您的完整代码修复:



  // Vertex shader programvar VSHADER_SOURCE ='attribute vec4 a_Position; \\\
'+'void main(){\\\
'+'gl_Position = a_Position; \\\
'+'gl_PointSize = 10.0; \\\
'+'} \\\
'; // Fragment shader programvar FSHADER_SOURCE ='precision mediump float; \\\
'+'uniform vec4 u_FragColor; \\\
'+'void main(){\\\
'+'gl_FragColor = u_FragColor; \\\
'+'} \\\
'; var mousePressed = false; //如果鼠标按下则保持boolean var leftClick = false; //保持boolean,如果左击被按下var rightClick = false; //保持布尔值,如果右击被按下函数main(){// Retrieve< canvas> element var canvas = document.getElementById('webgl'); canvas.oncontextmenu = function(e){e.preventDefault(); }; //获取WebGL的渲染上下文// var gl = getWebGLContext(canvas); var gl = canvas.getContext('webgl'); if(!gl){console.log('Failed to get the rendering context for WebGL');返回; } //初始化着色器if(!initShaders(gl,VSHADER_SOURCE,FSHADER_SOURCE)){console.log('初始化着色器失败。返回; } //获取a_Position的存储位置var a_Position = gl.getAttribLocation(gl.program,'a_Position'); if(a_Position< 0){console.log('Failed to get the storage location of a_Position');返回; } //获取u_FragColor的存储位置var u_FragColor = gl.getUniformLocation(gl.program,'u_FragColor'); if(!u_FragColor){console.log('Failed to get the storage location of u_FragColor');返回; } //注册函数(事件处理程序)要在鼠标mousePressed上调用canvas.onmousedown = function(ev){console.log('f1 called'); //识别哪个点击被按下switch(ev.which){case 1:// leftClick click leftClick = true;打破; case 3:// rightClick click rightClick = true;打破; } //鼠标点击被按下mousePressed = true; // call function //console.log('calling f1'); // drawDots(ev,gl,canvas,a_Position,u_FragColor,false); // drawDots(ev,gl,a_Position,u_FragColor,false); }; canvas.onmousemove = function(ev){console.log('f2 called'); if(mousePressed){console.log('calling drawDots'); drawDots(ev,gl,canvas,a_Position,u_FragColor,true); } // drawDots(ev,gl,a_Position,u_FragColor,true); }; canvas.onmouseup = function(ev){console.log('f3 called'); mousePressed = false; leftClick = false; rightClick = false; }; //指定要清除< canvas>的颜色gl.clearColor(0.0,0.0,0.0,1.0); console.log('clearColor call'); // Clear< canvas> gl.clear(gl.COLOR_BUFFER_BIT); console.log('clear call');} var g_points = []; //鼠标位置的数组mousePressedvar g_colors = []; function drawDots(ev,gl,canvas,a_Position,u_FragColor,down)// function drawDots(ev,gl,a_Position,u_FragColor,down){console.log('drawDots called' var rect = ev.target.getBoundingClientRect(); var x = ev.clientX; //鼠标指针的x坐标var y = ev.clientY; //鼠标指针的y坐标x =((x-rect.left) - canvas.width / 2)/(canvas.width / 2); y =(canvas.height / 2-(y-rect.top))/(canvas.height / 2); // For left click if(down == true&& leftClick == true){console.log('called left'); //将坐标存储到g_points数组g_points.push(x); g_points.push(y); // Store the color g_colors.push([1.0,0.0,0.0,1.0]); // Clear< canvas> gl.clear(gl.COLOR_BUFFER_BIT); var len = g_points.length; for(var i = 0; i

 < html& text / javascript> function initShaders(gl,vertexStr,fragmentStr){var fragmentShader = getShader(gl,fragmentStr,true); var vertexShader = getShader(gl,vertexStr,false); gl.program = gl.createProgram(); gl.attachShader(gl.program,vertexShader); gl.attachShader(gl.program,fragmentShader); gl.linkProgram(gl.program); if(!gl.getProgramParameter(gl.program,gl.LINK_STATUS)){alert(Could not initialise shaders); } gl.useProgram(gl.program); return true;} function getShader(gl,str,isFrag){var shader; if(isFrag){shader = gl.createShader(gl.FRAGMENT_SHADER); } else {shader = gl.createShader(gl.VERTEX_SHADER); } gl.shaderSource(shader,str); gl.compileShader(shader); if(!gl.getShaderParameter(shader,gl.COMPILE_STATUS)){alert(gl.getShaderInfoLog(shader)); return null; } return shader;}< / script>< body onload =main();> < canvas id =webglstyle =border:none; width =500height =500>< / canvas>< / body>< / html>   

I'm having trouble changing change the color when you from left to right button. Holding down the left mouse button and moving it inside the canvas should draw a trajectory of the mouse in motion of red dots and blue dots for when you hold down the right mouse button.

Problem is: once you drawn with the left button and go the right button it changes the color drawn by left button, and vise versa.

Need help or hints on how to fix this. Thank you.

javascript:

// Vertex shader program
var VSHADER_SOURCE =
    'attribute vec4 a_Position;\n' +
    'void main() {\n' +
    '  gl_Position = a_Position;\n' +
    '  gl_PointSize = 10.0;\n' +
    '}\n';

// Fragment shader program
var FSHADER_SOURCE =
    'precision mediump float;\n' +
    'uniform vec4 u_FragColor;\n' + 
    'void main() {\n' +
    '  gl_FragColor = u_FragColor;\n' +
    '}\n';

 var mousePressed = false;      // Holds boolean if mouse is pressed down
 var leftClick = false;         // Holds boolean if left click is pressed down
 var rightClick = false;        // Holds boolean if right click is pressed down

 function main() 
 {
    // Retrieve <canvas> element
    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;
    }

    // Get the storage location of a_Position
    var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
    if (a_Position < 0) 
    {
        console.log('Failed to get the storage location of a_Position');
        return;
    }

    // Get the storage location of u_FragColor
    var u_FragColor = gl.getUniformLocation(gl.program, 'u_FragColor');
    if (!u_FragColor) 
    {
        console.log('Failed to get the storage location of u_FragColor');
        return;
    }

    // Register function (event handler) to be called on a mouse mousePressed
    canvas.onmousedown = function(ev)
    { 
    console.log('f1 called');
        // Identify which click is being press down
        switch (ev.which)
        {
            case 1:         // leftClick click
            leftClick = true;
            break;
            case 3:         // rightClick click
            rightClick = true;
            break;
        }

        // Mouse click is being pressed down
        mousePressed = true;

        // call function
        //console.log('calling f1');
        //drawDots(ev, gl, canvas, a_Position, u_FragColor, false); 
        //drawDots(ev, gl, a_Position, u_FragColor, false); 
    };

    canvas.onmousemove = function(ev)
    {
        console.log('f2 called');
        if (mousePressed)
        {
            console.log('calling drawDots');
            drawDots(ev, gl, canvas, a_Position, u_FragColor, true); 
        }
            //drawDots(ev, gl, a_Position, u_FragColor, true);
    };

    canvas.onmouseup = function(ev)
    {
        console.log('f3 called');
        mousePressed = false;
        leftClick = false;
        rightClick = false;
    };

    // Specify the color for clearing <canvas>
    gl.clearColor(0.0, 0.0, 0.0, 1.0);
    console.log('clearColor call');

    // Clear <canvas>
    gl.clear(gl.COLOR_BUFFER_BIT);
    console.log('clear call');
}

var g_points = []; // The array for the position of a mouse mousePressed

function drawDots(ev, gl, canvas, a_Position, u_FragColor, down) 
//function drawDots(ev, gl, a_Position, u_FragColor, down)
{
    console.log('drawDots called');
    var rect = ev.target.getBoundingClientRect() ;

    var x = ev.clientX; // x coordinate of a mouse pointer
    var y = ev.clientY; // y coordinate of a mouse pointer

    x = ((x - rect.left) - canvas.width/2)/(canvas.width/2);
    y = (canvas.height/2 - (y - rect.top))/(canvas.height/2);

    // For left click
    if (down == true && leftClick == true)
    {
        console.log('called left');
        // Store the coordinates to g_points array
        g_points.push(x); g_points.push(y);

        // Clear <canvas>
        gl.clear(gl.COLOR_BUFFER_BIT);

        var len = g_points.length;

        for(var i = 0; i < len; i += 2) 
        {
            // Pass the position of a point to a_Position variable
            gl.uniform4f(u_FragColor, 1.0, 0.0, 0.0, 1.0);
            gl.vertexAttrib3f(a_Position, g_points[i], g_points[i+1], 0.0);


            // Draw
            gl.drawArrays(gl.POINTS, 0, 1);
        }
    }
    // Right click
    else if (down == true && rightClick == true)
    {
        console.log('called right');
        // Store the coordinates to g_points array
        g_points.push(x); g_points.push(y);

        // Clear <canvas>
        gl.clear(gl.COLOR_BUFFER_BIT);

        var len = g_points.length;
        for(var i = 0; i < len; i += 2) 
        {
            // Pass the position of a point to a_Position variable
            gl.uniform4f(u_FragColor, 0.0, 0.0, 1.0, 1.0);
            gl.vertexAttrib3f(a_Position, g_points[i], g_points[i+1], 0.0);


            // Draw
            gl.drawArrays(gl.POINTS, 0, 1);
        }
    }
}

解决方案

For each point you add to g_points you need to remember what color the point was created as. So you can create another array to keep track of the point colors.

var g_points = []; // The array for the position of a mouse mousePressed
var g_colors = []; 

And add the color to the array every time you add a point.

// Store the coordinates to g_points array
g_points.push(x); g_points.push(y);

// Store the color
g_colors.push([1.0, 0.0, 0.0, 1.0]);

Then update your for loop to use the given color for each point.

for(var i = 0; i < len; i += 2) 
{
    // Pass the position of a point to a_Position variable
    gl.uniform4fv(u_FragColor, g_colors[i/2]);
    gl.vertexAttrib3f(a_Position, g_points[i], g_points[i+1], 0.0);


    // Draw
    gl.drawArrays(gl.POINTS, 0, 1);
}

Remember to update both the left click code and the right click code to store and use the color.

Here is your full code with the fix:

// Vertex shader program
var VSHADER_SOURCE =
    'attribute vec4 a_Position;\n' +
    'void main() {\n' +
    '  gl_Position = a_Position;\n' +
    '  gl_PointSize = 10.0;\n' +
    '}\n';

// Fragment shader program
var FSHADER_SOURCE =
    'precision mediump float;\n' +
    'uniform vec4 u_FragColor;\n' + 
    'void main() {\n' +
    '  gl_FragColor = u_FragColor;\n' +
    '}\n';

 var mousePressed = false;      // Holds boolean if mouse is pressed down
 var leftClick = false;         // Holds boolean if left click is pressed down
 var rightClick = false;        // Holds boolean if right click is pressed down

 function main() 
 {
    // Retrieve <canvas> element
    var canvas = document.getElementById('webgl');
    canvas.oncontextmenu = function (e) {
        e.preventDefault();
    };

    // Get the rendering context for WebGL
    //var gl = getWebGLContext(canvas);
    var gl = canvas.getContext('webgl');
    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;
    }

    // Get the storage location of a_Position
    var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
    if (a_Position < 0) 
    {
        console.log('Failed to get the storage location of a_Position');
        return;
    }

    // Get the storage location of u_FragColor
    var u_FragColor = gl.getUniformLocation(gl.program, 'u_FragColor');
    if (!u_FragColor) 
    {
        console.log('Failed to get the storage location of u_FragColor');
        return;
    }

    // Register function (event handler) to be called on a mouse mousePressed
    canvas.onmousedown = function(ev)
    { 
    console.log('f1 called');
        // Identify which click is being press down
        switch (ev.which)
        {
            case 1:         // leftClick click
            leftClick = true;
            break;
            case 3:         // rightClick click
            rightClick = true;
            break;
        }

        // Mouse click is being pressed down
        mousePressed = true;

        // call function
        //console.log('calling f1');
        //drawDots(ev, gl, canvas, a_Position, u_FragColor, false); 
        //drawDots(ev, gl, a_Position, u_FragColor, false); 
    };

    canvas.onmousemove = function(ev)
    {
        console.log('f2 called');
        if (mousePressed)
        {
            console.log('calling drawDots');
            drawDots(ev, gl, canvas, a_Position, u_FragColor, true); 
        }
            //drawDots(ev, gl, a_Position, u_FragColor, true);
    };

    canvas.onmouseup = function(ev)
    {
        console.log('f3 called');
        mousePressed = false;
        leftClick = false;
        rightClick = false;
    };

    // Specify the color for clearing <canvas>
    gl.clearColor(0.0, 0.0, 0.0, 1.0);
    console.log('clearColor call');

    // Clear <canvas>
    gl.clear(gl.COLOR_BUFFER_BIT);
    console.log('clear call');
}

var g_points = []; // The array for the position of a mouse mousePressed
var g_colors = []; 

function drawDots(ev, gl, canvas, a_Position, u_FragColor, down) 
//function drawDots(ev, gl, a_Position, u_FragColor, down)
{
    console.log('drawDots called');
    var rect = ev.target.getBoundingClientRect() ;

    var x = ev.clientX; // x coordinate of a mouse pointer
    var y = ev.clientY; // y coordinate of a mouse pointer

    x = ((x - rect.left) - canvas.width/2)/(canvas.width/2);
    y = (canvas.height/2 - (y - rect.top))/(canvas.height/2);

    // For left click
    if (down == true && leftClick == true)
    {
        console.log('called left');
        // Store the coordinates to g_points array
        g_points.push(x); g_points.push(y);

        // Store the color
        g_colors.push([1.0, 0.0, 0.0, 1.0]);

        // Clear <canvas>
        gl.clear(gl.COLOR_BUFFER_BIT);

        var len = g_points.length;

        for(var i = 0; i < len; i += 2) 
        {
            // Pass the position of a point to a_Position variable
            gl.uniform4fv(u_FragColor, g_colors[i/2]);
            gl.vertexAttrib3f(a_Position, g_points[i], g_points[i+1], 0.0);


            // Draw
            gl.drawArrays(gl.POINTS, 0, 1);
        }
    }
    // Right click
    else if (down == true && rightClick == true)
    {
        console.log('called right');
        // Store the coordinates to g_points array
        g_points.push(x); g_points.push(y);

        // Store the color
        g_colors.push([0.0, 0.0, 1.0, 1.0]);

        // Clear <canvas>
        gl.clear(gl.COLOR_BUFFER_BIT);

        var len = g_points.length;
        for(var i = 0; i < len; i += 2) 
        {
            // Pass the position of a point to a_Position variable
            gl.uniform4fv(u_FragColor, g_colors[i/2]);
            gl.vertexAttrib3f(a_Position, g_points[i], g_points[i+1], 0.0);


            // Draw
            gl.drawArrays(gl.POINTS, 0, 1);
        }
    }
}

<html>
<script type="text/javascript">
function initShaders(gl, vertexStr, fragmentStr) {
    var fragmentShader = getShader(gl, fragmentStr, true);
    var vertexShader = getShader(gl, vertexStr, false);

    gl.program = gl.createProgram();
    gl.attachShader(gl.program, vertexShader);
    gl.attachShader(gl.program, fragmentShader);
    gl.linkProgram(gl.program);

    if (!gl.getProgramParameter(gl.program, gl.LINK_STATUS)) {
        alert("Could not initialise shaders");
    }

    gl.useProgram(gl.program);

    return true;
}

function getShader(gl, str, isFrag) {
    var shader;
    if (isFrag) {
        shader = gl.createShader(gl.FRAGMENT_SHADER);
    } else {
        shader = gl.createShader(gl.VERTEX_SHADER);
    }

    gl.shaderSource(shader, str);
    gl.compileShader(shader);

    if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
        alert(gl.getShaderInfoLog(shader));
        return null;
    }

    return shader;
}
</script>
<body onload="main();">
    <canvas id="webgl" style="border: none;" width="500" height="500"></canvas>
</body>
</html>

这篇关于按向左或向右按​​钮更改颜色时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆