Canvas

最近在学习 canvas,整理了一下常用的API~

获取上下文:drawing.getContext(‘2d’);

路径:beginPath(); closePath()

填充:fill() 填充样式: fillStyle
描边:stroke() 描边样式:strokeStyle
剪切:clip()

矩形(宽高单位是 px):fillRect(x, y, width, height) strokeRect() clearRect()
圆:arc(x, y, radius, startAngle, endAngle, true/false) (true:逆时针 false:顺时针)
弧:arcTo(x1, y1, x2, y2, radius)
线:moveTo(x, y) + lineTo(x, y)

文本:fillText(‘string’, x, y, 最大像素宽度) strokeText(‘string’, x, y, px-width)
设置文本属性: context.font = ‘文本样式 大小 字体’
context.textAlign = ‘start/end/left/right/center’ // 文本对齐方式,start 从左到右显示,end 从右到左显示
context.textBaseLine = ‘top/hanging/middle/alphabetic/ideographic/bottom’ // 文本的基线

旋转画布:rotate(angle)
移动坐标原点:translate(x, y)
缩放:scale(scaleX, scaleY)

线性渐变:var gradient = context.createLinearGradient(起点x,起点y,终点x,终点y)
添加渐变颜色:gradient.addColorStop(色标位置(0~1),颜色值)
context.fillStyle = gradient;

放射渐变:context.createRadialGradient(x1, y1, radius, x2, y2, radius)

图像:var imgData = context.getImageData(x, y, width, height) // 获取图像信息
context.putImageData(imgData, x, y) // 绘制图像
imgWidth, imgHeight, imgData: 数组,保存每个像素数据,每个像素4个数据(r,g,b,a)

画图:ctx.drawImage(img, x, y) // x y 是绘制图像的起点的坐标,img是 img元素 /另一个 canvas元素
ctx.drawImage(img, x, y, width, height) // 绘制图像的起点 和 宽高
ctx.drawImage(img, srcx, srcy, srcwidth, srcheight, targetx, targety, targetwidth, targetheight) // 原始图像的起点,宽高部分的图像 绘制到 上下文的坐标,宽高中

阴影:shadowColor shadowOffsetX shadowOffsetY shadowBlur