canvas

  • 该标签需要配合js一起使用
  • 可以绘制三角形、矩形、圆形等多种图案
  • 常用于游戏、动画、可视化数据等工作场景
  • 可以直接使用canvas标签测试出是否兼容
html 复制代码
<canvas width="500" height="500" style="border:1px solid">
    请使用支持canvas的主流浏览器查看
</canvas>

基本使用

  • index.html
html 复制代码
<canvas width = "500" height = "500" id = "cvs"></canvas> 
  • 三角形
js 复制代码
   const c = document.getElementById("cvs");
    // 三角形 起笔坐标(X,Y)
    c.moveTo(50, 50);
    // 点1
    c.lineTo(100, 100);
    // 点2
    c.lineTo(0, 100);
    // 点3
    c.closePath(); // 回到起笔位置 等同于 c.lineTo(50, 50);
    // 连接点位
    c.stroke();
  • 四边形
js 复制代码
   const c = document.getElementById("cvs");
     /* ... */
    // 清除路径
    c.beginPath();

    // 四边形
    c.moveTo(200, 200);
    // 点1
    c.lineTo(300, 200);
    // 点2
    c.lineTo(300, 300);
    // 点3
    c.lineTo(200, 300);
    // 点4
    c.lineTo(200, 200);

    c.lineWidth = '0';
    // 线条交界处样式
    c.lineJoin = 'miter'; // 'round' 圆角 'bevel' 斜切角
    // 线条折转样式
    c.lineCap = 'butt'; // 'round' 圆形 'square' 方形
    // 线条样式
    c.strokeStyle = '#000';
    // 填充
    // c.fill();
    // 连接点位
    c.stroke();

使用接口

  • 四边形
js 复制代码
    const c = document.getElementById("cvs");
    // 参数: (x, y, width, height)
    c.fillRect(100, 200, 100, 100);   // 填充四边形 左
    c.rect(200, 200, 100, 100);       // 无边无填充四边形 中  (看不见,但是存在)
    c.strokeRect(300, 200, 100, 100); // 边框四边形 右
  • 清空四边形画布
js 复制代码
// 参数: (x,y,width,height)
c.clearRect(0, 0, 500, 500);
  • 圆形
js 复制代码
    const c = cRef.current.getContext('2d');
    // 参数: (x, y , 正右(3点钟)方向为起点, Math.PI / 180 * 角度, 是否顺时针方向)
    c.arc(250, 250, 100, 0, Math.PI * 2, true);
    c.stroke();

样式保存

js 复制代码
    const c = cRef.current.getContext('2d');
    c.lineWidth = 2;
    c.strokeStyle = 'green';
    // 保存样式
    c.save();
    // 画个圆
    c.arc(100, 100, 100, 0, Math.PI * 2, true);
    // 重新起笔 (x + r, y)    (没有设置这个就会有图1的情况)
    c.moveTo(350, 250); // 下一个圆的圆心点 + 半径 就是它X轴的起点位置 
    // 重新画个圆
    c.arc(250, 250, 100, 0, Math.PI * 2, true);
    // 读取之前的样式
    c.stroke();
js 复制代码
    const c = cRef.current.getContext('2d');
    c.lineWidth = 2;
    c.strokeStyle = 'green';
    // 保存样式
    c.save();
    // 画个圆
    c.arc(100, 100, 100, 0, Math.PI * 2, true);

    // 清除路径
    c.beginPath();
    // 重新画个圆
    c.arc(250, 250, 100, 0, Math.PI * 2, true);
    // 读取之前的样式渲染
    c.stroke();

旋转、移动(连续使用效果可以叠加)

js 复制代码
c.translate(x, y); // 移动
c.rotate((Math.PI / 180) * 角度);  // 旋转
相关推荐
23级二本计科5 分钟前
前端 HTML + CSS + JavaScript
前端·css·html
踩着两条虫6 分钟前
VTJ.PRO「AI + 低代码」应用开发平台的后端模块系统
前端·人工智能·低代码
pany13 分钟前
程序员近十年新年愿望,都有哪些变化?
前端·后端·程序员
朱昆鹏18 分钟前
IDEA Claude Code or Codex GUI 插件【开源自荐】
前端·后端·github
HashTang19 分钟前
买了专业屏只当普通屏用?解锁 BenQ RD280U 的“隐藏”开发者模式
前端·javascript·后端
双向3319 分钟前
Agent智能体:2026年AI开发者必须掌握的自主系统革命
前端
мо仙堡杠把子ご灬19 分钟前
【无标题】
javascript
布列瑟农的星空19 分钟前
通用语法校验器tree-sitter——C++语法校验实践
前端
用户812748281512020 分钟前
libgui中的BufferQueueProducer加入堆栈CallStack编译报错问题-大厂企业实战项目难题
前端
明月_清风21 分钟前
从"请求地狱"到"请求天堂":alovajs 如何用 20+ 高级特性拯救前端开发者
前端·后端