问题
如何根据rgba刷成webgl的底色?
思路
rgba的格式为: rgba(1,1,0,1),可以根据正则,取出括号里面的每一个数字,再进行自己的逻辑处理(只取出不处理也可以),然后实用webgl的
.gl.clearColor(r, g, b, a)
写入进去。
示例代码
硬编码写入
```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>01-刷底色</title> <style> body { margin: 0; overflow: hidden; } #canvas { background-color: antiquewhite; } </style> </head> <body> <canvas id="canvas"></canvas> <script> const canvas = document.querySelector("#canvas"); canvas.width = window.innerWidth; canvas.height = window.innerHeight; //二维画笔 // const gl=canvas.getContext('2d'); //三维画笔 const gl = canvas.getContext("webgl"); //声明颜色 rgba gl.clearColor(1, 1, 0, 1); //刷底色 gl.clear(gl.COLOR_BUFFER_BIT); </script> </body> </html>
效果:
根据rgba写入
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>01-刷底色</title> <style> body { margin: 0; overflow: hidden; } #canvas { background-color: antiquewhite; } </style> </head> <body> <canvas id="canvas"></canvas> <script> const canvas = document.querySelector("#canvas"); canvas.width = window.innerWidth; canvas.height = window.innerHeight; //二维画笔 // const gl=canvas.getContext('2d'); //三维画笔 const gl = canvas.getContext("webgl"); //声明颜色 rgba gl.clearColor(1, 1, 0, 1); //刷底色 gl.clear(gl.COLOR_BUFFER_BIT); //css颜色 const rgbaCss = "rgba(255,100,0,1)"; //正则 const reg = RegExp(/\((.*)\)/); //捕捉数据 const rgbaStr = reg.exec(rgbaCss)[1]; console.log(rgbaStr); //加工数据 const rgba = rgbaStr.split(",").map((n) => parseInt(n)); console.log(rgba); const r = rgba[0] / 255; const g = rgba[1] / 255; const b = rgba[2] / 255; const a = rgba[3]; //声明颜色 rgba gl.clearColor(r, g, b, a); //刷底色 gl.clear(gl.COLOR_BUFFER_BIT); </script> </body> </html>
效果:
大功告成!!