Skip to content

Canvas

文字

js
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')

ctx.textBaseline = 'top'
ctx.font = `${fontSize}px serif`
ctx.fillStyle = fontColor
ctx.fillText('文字', 0, 0)

图片

加载图片

js
function createImgElement(src) {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.addEventListener('load', () => resolve(img), true)
    img.addEventListener('error', reject, true)
    img.src = src
  })
}

绘制图片

js
async function drawImage(url, x, y, width, height) {
  const ctx = canvas.getContext('2d')
  const img = await createImgElement(url)
  ctx.drawImage(img, x, y, width, height)
}

拖拽

缩放

下载画布作为图像

js
const canvas = document.getElementById('canvas')
const ctx = canvas.getContext('2d')

// Canvas code goes here
// ...

document.getElementById('download').addEventListener('click', (e) => {
  // Convert our canvas to a data URL
  const canvasUrl = canvas.toDataURL()
  // Create an anchor, and set the href value to our data URL
  const createEl = document.createElement('a')
  createEl.href = canvasUrl

  // This is the name of our downloaded file
  createEl.download = 'download-this-canvas'

  // Click the download button, causing a download, and then remove it
  createEl.click()
  createEl.remove()
})