我试图在WebGL中制作SVG(和其他2D矢量图形)渲染器 到目前为止,我已经弄清楚如何用三角形绘制Quadratic Bezier。
这是代码。
var createProgram = function ( vsSource, fsSource ) {
var vs = gl.createShader( gl.VERTEX_SHADER );
gl.shaderSource( vs, vsSource );
gl.compileShader( vs );
var fs = gl.createShader( gl.FRAGMENT_SHADER );
gl.shaderSource( fs, fsSource );
gl.compileShader( fs );
var program = gl.createProgram();
gl.attachShader( program, vs );
gl.attachShader( program, fs );
gl.linkProgram( program );
return program;
}
var vsSource = `
precision mediump float;
attribute vec2 vertex;
attribute vec2 attrib;
varying vec2 p;
void main(void) {
gl_Position = vec4(vertex, 0.0, 1.0);
p = attrib;
}
`;
var fsSource = `
precision mediump float;
varying vec2 p;
void main(void) {
if (p.x*p.x - p.y > 0.0) {
// discard;
gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);
} else {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
}
`;
var canvas = document.querySelector( 'canvas' );
var gl = canvas.getContext( 'webgl' ) ||
canvas.getContext( 'experimental-webgl' );
gl.clearColor( 0.5, 0.5, 0.5, 1.0 );
var shapeData = [
-0.5, 0,
0.5, 0,
0, 1
];
var curveAttr = [
0, 0,
1, 1,
0.5, 0
];
var program = createProgram( vsSource, fsSource );
gl.useProgram( program );
var vertexLoc1 = gl.getAttribLocation( program, 'vertex' );
var attribLoc1 = gl.getAttribLocation( program, 'attrib' );
gl.clear( gl.COLOR_BUFFER_BIT );
gl.useProgram( program );
gl.enableVertexAttribArray(vertexLoc1);
gl.enableVertexAttribArray(attribLoc1);
var vertexBuffer1 = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer1 );
gl.bufferData( gl.ARRAY_BUFFER, new Float32Array( shapeData ), gl.STATIC_DRAW );
gl.vertexAttribPointer(vertexLoc1, 2, gl.FLOAT, false, 0, 0);
var vertexBuffer2 = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer2 );
gl.bufferData( gl.ARRAY_BUFFER, new Float32Array( curveAttr ), gl.STATIC_DRAW );
gl.vertexAttribPointer(attribLoc1, 2, gl.FLOAT, false, 0,0);
gl.drawArrays( gl.TRIANGLES, 0, shapeData.length / 2 );

<canvas></canvas>
&#13;
我的问题是如何绘制Cubic Bezier,就像上面一样。
我想应该用2个或几个三角形来完成。 而且,我知道现在将Cubic Bezier转换为Quadratic。