canvas绘制图形

目录

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);

 

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值