canvas绘制
- 在html中嵌入<canvas></canvas>标签
- 使用js得到canvas引用
canvas操作
- 设置canvas的宽高
var width = canvas.width = window.innerWidth;
var height = canvas.height = window.innerHeight;
- 得到可绘制的区域
var ctx = canvas.getContext('2d')
矩形
ctx.fillStyle = 'rgba(0, 0, 0, 0.25)';
ctx.fillRect(25, 100, 50, 50);
边框
ctx.strokeStyle = 'rgb(255, 255, 255)';//颜色
ctx.strokeRect(25, 25, 175, 200);//位置
ctx.lineWidth = 5;//线条宽度
绘制路径
beginPath() //调用这个函数 从笔所在位置开始绘制
moveTo(x,y)//移动到另一个点 无路径
fill() //填充绘制的路径
stroke()
lineTo(x,y)//移动到另一个点,有路径
arc(x,y,r,开始弧度,结束弧度,是否顺时针)
也可以使用 lineWidth and fillStyle/strokeStyle像前面一样
一个典型的绘制代码
ctx.fillStyle = 'rgb(255, 0, 0)';
ctx.beginPath();
ctx.moveTo(50, 50);
// draw your path
ctx.fill();
function degToRad(degrees) {//角度转弧度
return degrees * Math.PI / 180;
};
文本绘制
fillText()
strokeText()//这两个函数都接受三个参数 要绘制的文本字符串,以及文本框左上角的X和Y坐标(实际上,是你绘制的文本框)。
例子:
ctx.strokeStyle = 'white'
ctx.lineHeight = 1
ctx.font = '36px airal'
ctx.strokeText('Canvas Text',50,50)
ctx.fillStyle = 'red'
ctx.font = '48px georgia'
ctx.fillText('Canvas Text',50,150)
在画布上绘制图像
drawImage()//接受9个参数 图片的位置 x、y代表起始位置 四五个参数代表图片的宽高
循环和动画
translate(x,y)//移动 起始点(坐标轴中心)到某个点