本章主要介绍canvas实现2D动画效果,记录canvas的基本使用语法。
1. html文档中创建canvas区域
//创建一个长800px 宽800px 的区域用于渲染canvas内容
<canvas id="canvas" width="800" height="800"></ canvas>
2. js中引入canvas
let canvas = = document.getElementById('canvas')
let ctx = canvas.getContext('2d') //获取绘制画笔
3. 绘制矩形
//填充矩形(x, y, width, height)
ctx.fillRect(10, 10, 600, 600)
//边框矩形
ctx.strokeRect(10, 10, 600, 600)
//清除矩形区域
ctx.clearRect(10, 10, 600, 600)
4. 添加样式和颜色
ctx.fillStyle = '#888' //填充颜色
ctx.strokeStyle = 'grey' //边框颜色
ctx.lineWidth = 2 //线粗细
ctx.lineJoin = 'round' //线条与线条连接处样式 (round 圆角,bevel 斜角,miter 直角)
ctx.lineCap = 'round' //每条线段末端的属性(butt 方形, round 圆形,square 方形)
ctx.save() //保存当前绘图状态
ctx.restore() //恢复到最近的保存状态
ctx.font = "30px Arial" //设置字体样式
ctx.fillText("你好", 10, 50) //填充实心字体
ctx.strokeText("你好", 10, 50) //填充空心字体
5. 路径
ctx.beginPath() //路径开始
ctx.closePath() //路径结束
ctx.moveTo(x, y) //路径起点
ctx.lineTo(x, y) //画路径
ctx.stroke() //填充渲染路径
ctx.fill() //填充渲染路径
ctx.arc(x, y, radius, startAngle, endAngle, true / false) 画圆(弧)
ctx.arcTo(x1, y1, x2, y2, radius) //画圆弧
ctx.quadraticCurveTo(x1, y1, x, y) //二次贝塞尔曲线
ctx.bezierCurveTo(x1, y1, x2, y2, x, y) //三次贝塞尔曲线
6. 变换
//移动原点位置 translate(x, y)
ctx.translate(10, 10)
//旋转角度(顺时针) rotate(angle)
ctx.rotate(Math.PI / 2)
//横轴和纵轴的缩放(正值)scale(x,y)
ctx.scale(2,4)
7. 图片
//drawImage (image, x, y, width, height)
let img = new Image()
img.src = "img/01.png"
img.onload = function(){
ctx.drawImage(img, 0, 0, 600, 400)
}
//设置背景(repeat, repeat-X, repeat-Y, no-repeat)
ctx.createPattern(image, repetition)
8. 渐变
//线性渐变(x1, y1, x2, y2)
//addColorStop()规定渐变对象中的颜色和停止位置,position值范围为0~1
let a = ctx.createLinearGradient(0, 0, 100, 0)
a.addColorStop(0, 'grey')
a.addColorStop(1,'blue')
//径向渐变(x1, y1, r1, x2, y2, r2)
let b = ctx.createRadialGradient(0, 0, 5, 50, 50, 10)
b.addColorStop(0,'pink')
b.addColorStop(1,'red')
9. 重复帧数: 在浏览器下次重绘之前继续更新下一帧
function render(){
//画笔设置的各种参数代码
requestAnimationFrame(render)
}
10. 补充
// 控制源图像在目标上的显示方式,类型如下图
ctx.globalCompositeOperation = "destination-out"
//从原始画布上剪切任意形状和尺寸
ctx.clip()
以上记录了常见的canvas绘制2D图形的基本语法,全部语法规则详情可参考链接:https://www.runoob.com/tags/ref-canvas.html