"오프스크린 렌더링은 보이지 않는 창에서 웹 페이지를 그려 이미지로 만드는 기술" — PDF 생성, 썸네일 생성, 서버사이드 렌더링 등에 활용됩니다.


오프스크린 렌더링이란

화면에 표시하지 않는 BrowserWindow에서 웹 콘텐츠를 렌더링하고, 그 결과를 비트맵 이미지로 받는 기술입니다.

JAVASCRIPT
const { BrowserWindow } = require('electron');

const offscreen = new BrowserWindow({
  show: false,
  webPreferences: {
    offscreen: true,   // 오프스크린 렌더링 활성화
  },
});

offscreen.webContents.setFrameRate(30); // 프레임 레이트 설정

// 프레임이 렌더링될 때마다 이벤트 발생
offscreen.webContents.on('paint', (event, dirty, image) => {
  // image는 NativeImage 객체
  const bitmap = image.toBitmap();
  const png = image.toPNG();
  const size = image.getSize(); // { width, height }
});

offscreen.loadURL('https://example.com');

웹 페이지를 이미지로 캡처

JAVASCRIPT
async function captureWebPage(url, options = {}) {
  const win = new BrowserWindow({
    show: false,
    width: options.width || 1280,
    height: options.height || 720,
    webPreferences: {
      offscreen: true,
    },
  });

  await win.loadURL(url);

  // 페이지 렌더링 완료 대기
  await new Promise(resolve => setTimeout(resolve, 2000));

  const image = await win.webContents.capturePage();
  win.destroy();

  return image.toPNG();
}

// 사용 예시
ipcMain.handle('capture:webpage', async (_event, url) => {
  const pngBuffer = await captureWebPage(url);
  const savePath = path.join(app.getPath('temp'), `capture-${Date.now()}.png`);
  await fs.promises.writeFile(savePath, pngBuffer);
  return savePath;
});

썸네일 생성

JAVASCRIPT
async function generateThumbnail(htmlContent, width = 320, height = 180) {
  const win = new BrowserWindow({
    show: false,
    width: 1280,
    height: 720,
    webPreferences: { offscreen: true },
  });

  await win.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(htmlContent)}`);
  await new Promise(resolve => setTimeout(resolve, 1000));

  const image = await win.webContents.capturePage();
  win.destroy();

  // 리사이즈
  return image.resize({ width, height }).toPNG();
}

PDF 생성

JAVASCRIPT
async function generatePDF(url) {
  const win = new BrowserWindow({
    show: false,
    webPreferences: { offscreen: true },
  });

  await win.loadURL(url);
  await new Promise(resolve =>
    win.webContents.on('did-finish-load', resolve)
  );

  const pdfData = await win.webContents.printToPDF({
    printBackground: true,
    pageSize: 'A4',
    margins: { top: 1, bottom: 1, left: 1, right: 1 },
  });

  win.destroy();
  return pdfData;
}

주의사항

  • 오프스크린 윈도우도 메모리와 CPU를 소비하므로 사용 후 destroy() 필수
  • setFrameRate()로 불필요한 렌더링 빈도를 줄이기
  • GPU 가속이 비활성화될 수 있어 일부 CSS 효과가 다르게 보일 수 있음

면접 포인트 정리

  • 오프스크린 렌더링은 webPreferences.offscreen: true로 활성화
  • paint 이벤트로 실시간 프레임을 비트맵으로 받을 수 있음
  • PDF, 썸네일, 스크린샷 생성에 활용
  • 사용 후 반드시 destroy()로 윈도우를 정리해야 메모리 누수 방지

오프스크린 렌더링까지 다뤘으면, 이제 고급 주제인 보안으로 넘어갑시다.

댓글 로딩 중...