目录
1、canvas绘制矩形
2、canvas绘制线
3、canvas绘制圆
4、canvas绘制多圈动画圆
HTML5<canvas>元素用于图形的绘制,Canvas API主要聚焦于2D图形。
1、canvas绘制矩形
canvas是一个二维网格,左上角坐标为(0,0),横轴为x轴,纵轴为y轴。
<!-- 设置canvas元素 -->
<canvas id = "canvas" width="200" height="200"></canvas>...// 获取canvas元素
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
// 执行绘制,fillRect(x,y,width,height)
ctx.fillRect(10,10,100,200);
ctx.fillstyle = "#333";
2、canvas绘制线
moveTo(x,y)定义线条开始坐标;
lineTo(x,y)定义线条结束坐标。
<!-- 设置canvas元素 -->
<canvas id = "canvas" width="200" height="200"></canvas>...// 获取canvas元素
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
ctx.moveTo(10,20);
ctx.lineTo(400,500);
ctx.strokeStyle = "##ff2d51";
ctx.stroke();
3、canvas绘制圆
arc(x,y,r,startAngle,endAngle,anticlockwise):以(x,y)为圆心,r为半径,从startAngle弧度开始到endAngle弧度结束,anticlockwise为布尔值,true表示逆时针,false表示顺时针。
<!-- 设置canvas元素 -->
<canvas id = "canvas" width="200" height="200"></canvas>...// 获取canvas元素
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.arc(150,150,100,0,Math.PI*2);
ctx.closePath();
// 填充颜色
ctx.fillStyle = "#333";
ctx.fill();
// 描边颜色
ctx.strokeStyle = "#ff2d51";
// 描边宽度
ctx.lineWidth = 10;
ctx.stroke();
4、canvas绘制多圈动画圆
<!-- 设置canvas元素 -->
<canvas id = "canvas" width="200" height="200"></canvas>...var radius = 50;
var increase = true;// 获取canvas元素
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");function draw() {// 清楚给定矩形内的形状ctx.clearRect(0, 0, canvas.width, canvas.height);ctx.beginPath();ctx.arc(150, 150, radius, 0, Math.PI * 2);ctx.closePath();ctx.fillStyle = "#ff2d51";ctx.fill();ctx.beginPath();ctx.arc(150, 150, 50, 0, Math.PI * 2);ctx.closePath();ctx.fillStyle = "#333";ctx.fill();if (radius > 100) {increase = false;} else if (radius < 50) {increase = true;}if (increase) {radius++;console.log("banjings");} else {radius--;}
}
setInterval(draw, 20);