WebGL blit纹理到画布 [英] WebGL blit texture to canvas
问题描述
在WebGL中将纹理拼接到HTML canvas的最干净的方法是什么。
What is the cleanest way of blitting a texture to the HTML canvas in WebGL. I could see setting up an orthographic projection and rendering a textured quad, but is there a cleaner way?
推荐答案
什么意思是什么意思?将纹理拼接到HTML5 Canvas?你的意思是只是画一个纹理1x1像素的画布?不需要正交投影。
What to mean "blitting a texture to the HTML5 Canvas"? Do you mean just drawing a texture 1x1 pixel to the canvas? No need for a orthographic projection. The simplest thing is either make a unit quad and scale or make a quad in pixel coords and draw.
这里是像素坐标quad shader
Here's the pixel coord quad shader
attribute vec2 a_position;
attribute vec2 a_texCoord;
uniform vec2 u_resolution;
varying vec2 v_texCoord;
void main() {
// convert the rectangle from pixels to 0.0 to 1.0
vec2 zeroToOne = a_position / u_resolution;
// convert from 0->1 to 0->2
vec2 zeroToTwo = zeroToOne * 2.0;
// convert from 0->2 to -1->+1 (clipspace)
vec2 clipSpace = zeroToTwo - 1.0;
gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);
v_texCoord = a_texCoord;
}
这个例子来自这里。 (http://games.greggman.com/game/webgl-image-processing/)
That example is from here. (http://games.greggman.com/game/webgl-image-processing/)
单位四版本的缩放偏移量为
The scale offset of a unit quad version would be
attribute vec2 a_position;
attribute vec2 a_texCoord;
uniform vec2 u_offset;
uniform vec2 u_scale;
varying vec2 v_texCoord;
void main() {
gl_Position = vec4(a_position * u_scale + u_offset, 0, 1);
v_texCoord = a_texCoord;
}
最后,在任一种情况下,您都可以使用3x3矩阵数学简化代码
Finally in either case you can simplify the code by using 3x3 matrix math
attribute vec2 a_position;
uniform mat3 u_matrix;
void main() {
// Multiply the position by the matrix.
gl_Position = vec4((u_matrix * vec3(a_position, 1)).xy, 0, 1);
}
[
2 / canvasWidth, 0, 0,
0, -2 / canvasHeight, 0,
-1, 1, 1
]
将从像素转换为clipspace。
Will convert from pixels to clipspace. A matrix of
[
imageWidth, 0, 0,
0, imageHeight, 0,
0, 0, 1
]
将从单位四舍五入转换为大小
Will convert from a unit quad to the size of your image.
进入所有的矩阵数学对于这个答案来说似乎太多了,但如果你有兴趣,你可以在这里找到参见 http://games.greggman.com/game/webgl-2d-matrices/
Going into all the matrix math seems like too much for this answer but if you're interested you can find it here See http://games.greggman.com/game/webgl-2d-matrices/
这篇关于WebGL blit纹理到画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!