↓ 跳过正文

Zdog JavaScript Frontend

Zdog:伪 3D 的 JavaScript 库,顺便给光复节挂一面太极旗

Zdog 是一个面向 canvas 和 SVG 的小巧伪 3D 引擎:图形在 3D 空间里,画出来却是扁平的。这里有一段最小示例,以及我为光复节做的太极旗 CodePen。

Zdog:伪 3D 的 JavaScript 库,顺便给光复节挂一面太极旗

下周就是韩国的光复节了。按传统,这一天大家会在自家门口或公寓窗外挂起国旗。为了纪念这个日子,顺便练练JavaScript,我决定借机会试一个挺不错的伪3D库。

光复节(8 月 15 日)是韩国纪念 1945 年摆脱日本殖民统治的节日。Zdog 是一个小巧的 JavaScript 库,用来在 <canvas> 或 SVG 上画有 3D 感的插画。图形在 3D 空间里有真实的位置,也能像 3D 物体一样转动,但画出来是扁平的图形,所以效果更像一张能转着看的扁平插画,而不是 3D 渲染。做面旗子这种简单的东西正合适。

Zdog 最小示例
#

两个图形、拖动旋转,再加一个动画循环:

<canvas class="zdog-canvas" width="240" height="240"></canvas>
<script src="https://unpkg.com/zdog@1/dist/zdog.dist.min.js"></script>
<script>
  const illo = new Zdog.Illustration({
    element: '.zdog-canvas',
    dragRotate: true, // drag to turn the scene
  });

  // a square, pushed back
  new Zdog.Rect({
    addTo: illo,
    width: 80,
    height: 80,
    translate: { z: -30 },
    stroke: 8,
    color: '#0047a0',
  });

  // a filled circle, pulled forward
  new Zdog.Ellipse({
    addTo: illo,
    diameter: 60,
    translate: { z: 30 },
    stroke: 8,
    color: '#cd2e3a',
    fill: true,
  });

  function animate() {
    illo.rotate.y += 0.02;
    illo.updateRenderGraph();
    requestAnimationFrame(animate);
  }
  animate();
</script>

每个图形用 addTo 加进场景,3D 的效果来自 translate.z:转动场景时,圆会绕到方块前面。updateRenderGraph() 负责更新并重绘整个场景,所以放在循环里。

官方文档
#

https://zzz.dog/

用到的代码可以在CodePen上看。

我的示例
#

See the Pen 광복절 by Jared Lynskey (@jared-lynskey) on CodePen.