在Webgl的位置获取颜色

时间:2017-05-19 12:29:40

标签: javascript html5 debugging canvas webgl

我想在Chrome控制台中调试我的html5画布。我想在位置(445,650)获得像素颜色。

我尝试使用此代码:

example
<canvas class="topleft" id="glcanvas" width="479" height="716" tabindex="1" contenteditable="true" style="cursor: default; width: 479px; height: 616px;"></canvas>

context
WebGLRenderingContext {vertexAttribDivisor: function, drawArraysInstanced: function, drawElementsInstanced: function, createVertexArray: function, deleteVertexArray: function…}

data
undefined

当我一个接一个地运行这些行时,我得到:

var pixels = new Uint8Array(
    4 * context.drawingBufferWidth * context.drawingBufferHeight
);
var x = 445; 
var y = 650;
context.readPixels(
    0,
    0,
    context.drawingBufferWidth,
    context.drawingBufferHeight,
    context.RGBA,
    context.UNSIGNED_BYTE,
    pixels
);
var pixelR = pixels[4 * (y * context.drawingBufferWidth + x)];
var pixelG = pixels[4 * (y * context.drawingBufferWidth + x) + 1];
var pixelB = pixels[4 * (y * context.drawingBufferWidth + x) + 2];
var pixelA = pixels[4 * (y * context.drawingBufferWidth + x) + 3];

如何获取非未定义数据?我只是想在HEX处获得像素颜色的位置(445,650)

第二次尝试:

pixels
Uint8Array(2268552) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0…]

所有像素都返回0,包括:

{{1}}

2 个答案:

答案 0 :(得分:1)

readPixels函数确实没有返回任何有用的东西。您感兴趣的像素数据将复制到pixels数组:

var pixels = new Uint8Array(
    4 * context.drawingBufferWidth * context.drawingBufferHeight
);
context.readPixels(
    0,
    0,
    context.drawingBufferWidth,
    context.drawingBufferHeight,
    context.RGBA,
    context.UNSIGNED_BYTE,
    pixels
);
// And here's components of a pixel on (x, y):
var pixelR = pixels[4 * (y * context.drawingBufferWidth + x)];
var pixelG = pixels[4 * (y * context.drawingBufferWidth + x) + 1];
var pixelB = pixels[4 * (y * context.drawingBufferWidth + x) + 2];
var pixelA = pixels[4 * (y * context.drawingBufferWidth + x) + 3];

此处xy是您要检查的像素的坐标。

答案 1 :(得分:-1)

它说,你的画布只有616的高度,所以像素在画布之外。