Canvas是HTML5新增的组件,它就像一块幕布,可以用JavaScript在上面绘制各种图表、动画等。
~本文多图少文,可放心食用
(一)绘制矩形
- 填充矩形
var canvas = document.getElementById('draw');
var ctx = canvas.getContext('2d') //取得2d上下文对象,WebGL取得3d上下文对象
ctx.fillStyle = 'rgb(0,0,255,0.5)'; //填充一个半透明的蓝色矩形
ctx.fillRect(0,0,200,100); //填充矩形坐标(0.0) width:200px height:100px
ctx.fillStyle = 'rgb(255,0,0,0.5)'; //填充一个半透明的红色矩形
ctx.fillRect(100,50,200,100);
ctx.clearRect(50,50,20,30); //擦除矩形区域
- 描边矩形
ctx.strokeStyle = 'rgb(0,255,0)'; //描边矩形
ctx.strokeRect(250,0,100,100);
(二) 绘制路径
- 画线
var canvas = document.getElementById('draw');
var ctx = canvas.getContext('2d') //取得2d上下文对象,WebGL取得3d上下文对象
ctx.beginPath(); //开始绘制新路径
ctx.moveTo(0,0); //起点坐标
ctx.lineTo(100,100); //终点,画线
ctx.closePath();//关闭绘制路径
ctx.stroke();
- 画弧
ctx.beginPath();
//圆心坐标(200,200),起始角度为0,终止角度为360度 Math.PI为180度。true表示逆时针画弧
ctx.arc(200,200,100,0,Math.PI * 2,true);
ctx.stroke();
- 画矩形路径
ctx.rect(0,0,200,100); //画矩形路径,并不是一个独立的形状
- 绘制三角形
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(100,0);//画一条横线
ctx.lineTo(100,100);//接着画一条竖线
ctx.closePath();//闭合这两条线
ctx.stroke();
绘制文本
ctx.font = "bold 50px Arial"; //设置字体样式:加粗 大小 字体
ctx.fillStyle = "rgb(255,0,0)"//红色
ctx.textAlign = "start"//文本居左 居右:end 居中:center
ctx.fillText("你好",0,100,200); //绘制文本 位置(100,100) 200:最大像素宽度
//ctx.strokeText(...);
绘制图像
首先需要在html上添加<img>
var img = document.images[0]; //表示获取页面的第一个img元素
img.onload = function () { //表示只有在图像加载完成后才能绘制
ctx.drawImage(img,10,10); //绘制图像,坐标(10,10),还可以添加两个参数限制图像大小。
};
添加阴影
//设置阴影
ctx.shadowColor = 'rgb(255,0,0)';
ctx.shadowBlur = 4; //模糊像素,越小越清晰
ctx.shadowOffsetX = 5; //形状或路径沿 x 轴方向的阴影偏移量,默认为 0。
ctx.shadowOffsetY = 3;// 形状或路径沿 y 轴方向的阴影偏移量,默认为 0。
ctx.font = "bold 50px Aprial"
ctx.fillText("你好",100,100,100);
添加渐变
- 线性渐变
var gradient = ctx.createLinearGradient(50,50,150,150); //定义一个线性渐变对象
gradient.addColorStop(0,'white'); //开始颜色
gradient.addColorStop(1,'red'); //结束颜色
ctx.fillStyle = "#000000"; //参照矩形
ctx.fillRect(0,0,100,100);
ctx.fillStyle = gradient; //渐变矩形
ctx.fillRect(50,50,100,100);
- 径向渐变
//定义一个径向渐变对象 前三个参数表示起点圆的圆心和半径,后三个表示终点圆的圆心和半径
var gradient = ctx.createRadialGradient(100,100,20,100,100,50);
gradient.addColorStop(0,'white');
gradient.addColorStop(1,'red');
ctx.fillStyle = "#000000"; //参照
ctx.fillRect(0,0,100,100);
ctx.fillStyle = gradient;
ctx.fillRect(50,50,100,100);