even

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

1、webgl入门案例

<body>
<canvas id="container"></canvas>
<script>
    // 获取canvas元素
    const canvas = document.getElementById('container')
    // 定义绘图的区域
    canvas.width = window.innerWidth
    canvas.height = window.innerHeight
    // 获取绘图的上下文
    const webgl = canvas.getContext('webgl')
    // 清空绘图区
    webgl.clearColor(0, 0, 0, 1)
    // 用指定的颜色清空绘图区
    webgl.clear(webgl.COLOR_BUFFER_BIT)
</script>
</body>

 rgba颜色与webgl中的颜色转换

const rgbaCss = 'rgba(255, 200, 2, 1)'

const reg = /rgba\((.*?)\)/

const colorText = rgbaCss.match(reg)

if (colorText && colorText[1]) {
  let [r, g, b, a] = colorText[1].split(',').map((item) => Number(item))

  // 清空绘图区
  webgl.clearColor(r / 255, g / 255, b / 255, a)

  // 用指定的颜色清空绘图区
  webgl.clear(webgl.COLOR_BUFFER_BIT)

}

使用three.js来做一个练习

import { Color } from 'three'

const init = (): void => {
  const canvas: HTMLCanvasElement | null = document.getElementById('container') as HTMLCanvasElement

  if (!canvas) return

  // 定义绘图的区域
  canvas.width = 1200
  canvas.height = 500
  // 获取绘图的上下文
  const webgl: WebGLRenderingContext | null = canvas.getContext('webgl')

  if (!webgl) return

  const color: Color = new Color('rgba(255, 0, 0, 1)') // new Color(1,0,0)

  const changeColor = () => {
    color.offsetHSL(0.01, 0, 0)  // hsl分别表示色相, 饱合度,亮度,这里只对色相做了偏移

    webgl.clearColor(color.r, color.g, color.b, 1)

    webgl.clear(webgl.COLOR_BUFFER_BIT)

    requestAnimationFrame(changeColor)  // 浏览器的api, 与浏览品质的渲染是同步的
  }

  changeColor()
}

init()

2、webgl的坐标系

webgl画布的建立和获取, 和canvas2d是一样的,但是两者之间还是有区别的

canvas2d画布的坐标

  • canvas 2d 坐标系的原点在左上角
  • canvas 2d 坐标系的y 轴方向是朝下的
  • canvas 2d 坐标系的坐标基底有两个分量,分别是一个像素的宽和一个像素的高,即1个单位的宽便是1个像素的宽,1个单位的高便是一个像素的高

 

 

 

 

 webgl画布的坐标

  • webgl坐标系的坐标原点在画布中心
  • webgl坐标系的y 轴方向是朝上的
  • webgl坐标基底中的两个分量分别是半个canvas的宽和canvas的高,即1个单位的宽便是半个个canvas的宽,1个单位的高便是半个canvas的高

 

 

 

 

posted on 2022-04-04 17:06  even_blogs  阅读(149)  评论(0编辑  收藏  举报