본문 바로가기
Html(js) & WebGL & Node.js

WebGL로 이미지와 텍스트 출력하기

by ERLite 2026. 3. 11.

🎨 WebGL로 이미지와 텍스트 출력하기

웹 브라우저에서 2D/3D 그래픽을 다루고 싶을 때 가장 강력한 도구 중 하나가 바로 WebGL(Web Graphics Library) 입니다. 이번 글에서는 WebGL을 활용해 이미지와 텍스트를 출력하는 방법을 학습용으로 정리해보겠습니다.

1. 기본 Canvas와 WebGL 초기화

먼저 HTML에서 <canvas> 요소를 가져와 WebGL 컨텍스트를 생성합니다.

javascript
const canvas = document.getElementById("glcanvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

const gl = canvas.getContext("webgl");
if (!gl) {
  alert("This browser does not support WebGL.");
}

여기서 gl은 WebGL의 핵심 객체로, 이후 모든 그래픽 작업은 이 객체를 통해 이루어집니다.

2. 셰이더(Shader) 작성

WebGL에서는 버텍스 셰이더(Vertex Shader)프래그먼트 셰이더(Fragment Shader) 두 가지가 필요합니다.

  • 버텍스 셰이더: 화면에 출력할 좌표를 계산
  • 프래그먼트 셰이더: 픽셀 색상이나 텍스처를 결정
glsl
// Vertex Shader
attribute vec2 aVertexPosition;
attribute vec2 aTextureCoord;
varying vec2 vTextureCoord;
void main(void) {
  gl_Position = vec4(aVertexPosition, 0.0, 1.0);
  vTextureCoord = aTextureCoord;
}

// Fragment Shader
precision mediump float;
varying vec2 vTextureCoord;
uniform sampler2D uSampler;
uniform vec4 u_color;
uniform int u_useColor;

void main(void) {
  if (u_useColor == 1) {
    gl_FragColor = u_color;
  } else {
    gl_FragColor = texture2D(uSampler, vTextureCoord);
  }
}

3. 텍스처 이미지 불러오기

이미지를 WebGL 텍스처로 변환해 출력할 수 있습니다.

javascript
function loadTextureImage(url, idx) {
  const texture = gl.createTexture();
  const image = new Image();
  image.onload = function() {
    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
    drawBuffers[idx].texture = texture;
    drawScene();
  };
  image.src = url;
}

이렇게 하면 원하는 이미지를 WebGL 화면에 출력할 수 있습니다.

4. 텍스트를 텍스처로 변환하기

WebGL은 직접 텍스트를 그릴 수 없기 때문에, Canvas 2D API를 활용해 텍스트를 그린 뒤 이를 텍스처로 변환합니다.

javascript
function loadTextureText(value, width, height, fontName, fontColor, fontSize) {
  const offCanvas = document.createElement("canvas");
  offCanvas.width = width;
  offCanvas.height = height;
  const ctx = offCanvas.getContext("2d");

  ctx.fillStyle = fontColor;
  ctx.font = `${fontSize}px ${fontName}`;
  ctx.textAlign = "center";
  ctx.textBaseline = "middle";
  ctx.fillText(value, offCanvas.width/2, offCanvas.height/2);

  const newTex = gl.createTexture();
  gl.bindTexture(gl.TEXTURE_2D, newTex);
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, offCanvas);
  return newTex;
}

5. 애니메이션 효과 (흘러가는 텍스트)

코드에서는 requestAnimationFrame을 활용해 텍스트가 좌우로 움직이는 흘러가는 자막 효과도 구현되어 있습니다.

javascript
async function animate() {
  flowTextX -= 1.5;
  if (flowTextX < 0) flowTextX = canvas.width;
  requestAnimationFrame(animate);
}

이렇게 하면 블로그나 웹 프로젝트에서 동적인 텍스트 연출을 할 수 있습니다.

6. 클릭 이벤트와 인터랙션

Canvas 클릭 시 좌표를 계산해 특정 영역을 선택하거나 강조할 수 있습니다.

javascript
canvas.addEventListener("click", function(event) {
  const rect = canvas.getBoundingClientRect();
  const x = event.clientX - rect.left;
  const y = event.clientY - rect.top;
  console.log(`Clicked at: ${x}, ${y}`);
});

✨ 마무리

이번 학습용 예제에서는 WebGL을 활용해 이미지와 텍스트를 출력하고, 애니메이션과 클릭 이벤트까지 구현하는 방법을 살펴봤습니다.

이 코드를 응용하면:

  • 블로그에 동적인 텍스트 배너 삽입
  • 웹 게임에서 UI 요소 출력
  • 인터랙티브한 데이터 시각화

등 다양한 활용이 가능합니다.

'Html(js) & WebGL & Node.js' 카테고리의 다른 글

Node.js REST API 서버 예제  (0) 2026.03.17
Node.js 설치  (0) 2026.03.17
Node.js WebSocket 샘플  (0) 2026.03.16
현재화면(Canvas)을 Node.js 서버로 저장  (0) 2026.03.13
WebGL로 동영상 출력하기  (0) 2026.03.13