1.基本用法
html
<canvas id="drawing" width="200" height="200"></canvas>
上下文
const drawing = document.getElementById('drawing') if (drawing.getContext) { const ctx = drawing.getContext('2d') }
导出img
const imgUrl = drawing.toDataUrl('image/png')
2. 2D上下文
2.1 填充和描边
ctx.strokeStyle = 'red'
ctx.fillStyle = 'green'
2.2 矩形
ctx.fillRect(10, 10, 50, 50) ctx.strokeRect(10, 10, 50, 50) ctx.clearRect(10, 10, 50, 50)
2.3 路径
ctx.beginPath() ctx.arc(10, 10, r, 0, 2 * Math.PI, false) ctx.arcTo(x1, y1, x2, y2, r) ctx.lineTo(x, y) ctx.moveTo(x, y)
ctx.closePath()
ctx.fill()
ctx.stroke()
ctx.clip()
2.4文本
ctx.font = 'bold 14px Arial' ctx.textAlign = 'start/center/end' ctx.textBaseLine = 'top/middle/bottom' ctx.fillText('test', x, y) ctx.mesureText()
2.5变换
ctx.rotate(angle) ctx.scale(scaleX, scaleY) ctx.translate(x, y) ctx.trnasform(m11, m12, m21, m22, dx, dy) m11 m12 dx m21 m22 dy 0 0 1 x = m11*x0 + m12*y0 + dx y = m21*x0 _ m22*y0 + dy
2.6图像
ctx.drawImage(image, 10, 50, 20, 30)
2.7阴影
ctx.shadowColor = 'red' ctx.shadowOffsetX = 5 ctx.shadowOffsetY = 5 ctx.shadowBlur = 4
2.8渐变
const gradient = ctx.createLinearGradient(30, 30, 70, 70) gradient.addColorStop(0, 'white') gradient.addColorStop(1, 'black') ctx.fillStyle = gradient const gradient = ctx.createRadialGradient(50, 50, 10, 50, 50, 30)
2.9模式
const pattern = ctx.createPattern(image, 'repeat/reapeatX/repeateY/no-repeat')
ctx.fillStyle = pattern
2.10使用图像数据
const imageData = ctx.getImageData(10, 5, 50, 50)
width, height, data
2.11 合成
ctx.globalAlpha = 0.5
ctx.gloabalCompositionOperation = 'source-over'