如何在 HTML canvas 中加載圖像

我正在使用 canvas npm 套件以 Canvas API 的方式在伺服器端繪製圖像。 注意:這是 Node.js 中在 canvas 中處理圖像的方式,不同於網頁瀏覽器中的處理方式。 載入 loadImage() 函式: const { createCanvas, loadImage } = require('canvas') 建立 canvas: const width = 1200 const height = 630 const canvas = createCanvas(width, height) const context = canvas.getContext('2d') 接下來呼叫 loadImage(),當圖像載入完成時它將返回一個 Promise: loadImage('./logo.png').then(image => { }) 也可以在 async 函式中使用: const image = await loadImage('./logo.png') 獲得圖像後,使用 drawImage 函式,並傳遞 x、y、width 和 height 參數: context.drawImage(image, 340, 515, 70, 70)