使用html2canvas时,当页面滚动位置发生变化,生成的图片会出现位置偏差,使用原生的canvas来生成图片则能更直观的看到图片生成的结果。

Draw.js 适用于浏览器的快速生成海报的 Javascript 库
Gzip 1.86KB Github/文档:https://github.com/HeartCNC/drawjs

常用API

  • fill() 填充
  • stroke() 线条
  • save() 保存当前环境的状态
  • restore() 返回之前保存过的路径状态和属性

颜色和属性

  • fillStyle 填充颜色
  • strokeStyle 线条颜色
  • font 字体样式
  • textAlign

以下canvas表示获取到的dom,cxt = canvas.getContext('2d') 设置canvas.width = 750, canvas.height = 1334 (移动端常见设计稿尺寸)

绘制图形

矩形

fillRect(x,y,width,height)

  • x 矩形左上角的 x 坐标
  • y 矩形左上角的 y 坐标
  • width 矩形的宽度,以像素计
  • height 矩形的高度,以像素计
cxt.fillStyle = 'blue'
cxt.fillRect(100, 20, 150, 100)
// 或者
cxt.rect(100, 20, 150, 100)
cxt.fill()
// 加边框
cxt.strokeStyle = '#000000'
cxt.stroke()

绘制图片

drawImage(img,sx,sy,swidth,sheight,x,y,width,height)

  • img 规定要使用的图像、画布或视频。
  • sx 可选。开始剪切的 x 坐标位置。
  • sy 可选。开始剪切的 y 坐标位置。
  • swidth 可选。被剪切图像的宽度。
  • sheight 可选。被剪切图像的高度。
  • x 在画布上放置图像的 x 坐标位置。
  • y 在画布上放置图像的 y 坐标位置。
  • width 可选。要使用的图像的宽度。(伸展或缩小图像)
  • height 可选。要使用的图像的高度。(伸展或缩小图像)
// 填充背景图
// 跨域需要image设置crossOrgin="anonymous"
const bg = await load('bg.jpg')
cxt.drawImage(bg, 0, 0, canvas.width, canvas.height, 0, 0, bg.width, bg.height)

文本

fillText(text, x, y, maxWidth)

  • text 规定在画布上输出的文本。
  • x 开始绘制文本的 x 坐标位置(相对于画布)。
  • y 开始绘制文本的 y 坐标位置(相对于画布)。
  • maxWidth 可选。允许的最大文本宽度,以像素计。
// 设置颜色
cxt.fillStyle = '#6f6f6f'
// 设置字体
cxt.font = 'normal 28px "Microsoft YaHei",Avenir,Helvetica Neue,Helvetica,Arial,sans-serif'
cxt.fillText('文本', 20, 50)

旋转、平移

translate(x,y) 移动画布坐标系的原点位置,相对位移

  • x 添加到水平坐标(x)上的值
  • y 添加到垂直坐标(y)上的值
// 向右边移动20,向下移动20
ctx.translate(20, 20);
// 向左边移动20,向上移动20
ctx.translate(-20, -20);
// 此时中心点仍然回到当初的位置

rotate(angle) 旋转画布

  • angle 旋转角度,以弧度计。如需旋转 ,可用下面的公式:5*Math.PI/180
// 配合平移可单独将某一对象旋转
const img = await load('img.png')
const pos = {
	x: 20,
	y: 60
}
//保存状态
cxt.save()
// 设置中心点
cxt.translate(
	pos.x + img.width / 2,
	pos.y + img.height / 2
)
// 旋转
cxt.rotate((Math.PI / 180) * 30)
// 还原中心点
cxt.translate(
	-(pos.x + img.width / 2),
	-(pos.y + img.height / 2)
)
// 绘制图像
cxt.drawImage(
	img,
	pos.x,
	pos.y,
	img.width,
	img.height
)
// 还原状态
cxt.restore()

裁剪圆形头像

clip()arc(x,y,r,sAngle,eAngle,counterclockwise)

  • x 圆的中心的 x 坐标。
  • y 圆的中心的 y 坐标。
  • r 圆的半径。
  • sAngle 起始角,以弧度计。(弧的圆形的三点钟位置是 0 度)。
  • eAngle 结束角,以弧度计。
  • counterclockwise 可选。规定应该逆时针还是顺时针绘图。False = 顺时针,true = 逆时针。
// 结合arc裁剪圆形头像
// 直径
const d = 100
// 半径
const r = width / 2
const avater = new Image()
avater.crossOrigin = 'anonymous'
avater.src = 'avater.jpg'
avater.onload = () => {
	ctx.save()
	// 画圆
	ctx.arc(66, 66, r, 0, 2 * Math.PI)
	// 裁剪
	ctx.clip()
	// 绘制图像
	ctx.drawImage(headimg, 66, 66, d, d)
	ctx.restore()
}