我試圖在WebGL中製作SVG(和其他2D矢量圖形)渲染器。
到目前爲止,我已經想出瞭如何繪製三角形的二次貝塞爾曲線。如何在WebGL中繪製Cubic 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>
我的問題是如何繪製三次Bezier,像上面。
我想應該用2個或幾個三角形來完成。 而且,我知道現在有必要將Cubic Bezier轉換爲Quadratic。
您可能會發現有用的兩個鏈接。 (1)[使用可編程圖形硬件的分辨率獨立曲線渲染](https://www.microsoft.com/zh-cn/research/publication/resolution-independent-curve-rendering-using-programmable-graphics-hardware/)和(2)[Bézier曲線入門](https://pomax.github.io/bezierinfo/) – gman