1 ) 通用结构代码
<canvas id="canvas">canvas>
<script>
const canvas = document.querySelector("#canvas");
canvas.width = 200;
canvas.height = 200;
const gl = canvas.getContext("webgl");
script>
2 ) 设置画布底色脚本
gl.clearColor(1, 1, 0, 1);
gl.clear(gl.COLOR_BUFFER_BIT);
3 ) 从样式中解析颜色并设置画布底色脚本
const rgbaCss = "rgba(0, 255, 0, 1)";
const reg = RegExp(/\((.*)\)/);
const rgbaStr = reg.exec(rgbaCss)[1];
const rgba = rgbaStr.split(",").map((n) => parseInt(n));
const r = rgba[0] / 255;
const g = rgba[1] / 255;
const b = rgba[2] / 255;
const a = rgba[3];
gl.clearColor(r, g, b, a);
gl.clear(gl.COLOR_BUFFER_BIT);
设置动态画布底色脚本
- 首先需要引入 three.js 的 Color 对象
<script type="module">
import { Color } from "https://unpkg.com/three/build/three.module.js";
const canvas = document.querySelector("#canvas");
canvas.width = 200;
canvas.height = 200;
const gl = canvas.getContext("webgl");
const color = new Color("rgba(255,0,0,1)");
!(function animate() {
color.offsetHSL(0.005, 0, 0);
const { r, g, b, a } = color;
gl.clearColor(r, g, b, a);
gl.clear(gl.COLOR_BUFFER_BIT);
requestAnimationFrame(animate);
})();
script>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18