vue 机器人走过的地方画线且对边界进行处理

javascript 复制代码
<template>
  <div>
    <canvas ref="canvas" width="400" height="400"></canvas>
  </div>
</template>

<script>
export default {
  mounted() {
    const canvas = this.$refs.canvas;
    const ctx = canvas.getContext('2d');

    // 定义画布大小和单元格大小
    const canvasWidth = canvas.width;
    const canvasHeight = canvas.height;
    const cellSize = 40;

    // 定义机器人的起点和路径
    const startX = cellSize / 2;
    const startY = cellSize / 2;
    const path = ['right', 'down', 'down', 'left', 'up', 'up', 'right', 'right', 'down'];

    // 设置起点
    let x = startX;
    let y = startY;

    // 绘制起点
    ctx.fillStyle = 'red';
    ctx.fillRect(x - 5, y - 5, 10, 10);

    // 遍历路径
    path.forEach(direction => {
      // 根据方向更新坐标
      if (direction === 'up') {
        if (y - cellSize >= 0) {
          y -= cellSize;
        }
      } else if (direction === 'down') {
        if (y + cellSize < canvasHeight) {
          y += cellSize;
        }
      } else if (direction === 'left') {
        if (x - cellSize >= 0) {
          x -= cellSize;
        }
      } else if (direction === 'right') {
        if (x + cellSize < canvasWidth) {
          x += cellSize;
        }
      }

      // 绘制路径
      ctx.strokeStyle = 'blue';
      ctx.lineWidth = 2;
      ctx.beginPath();
      ctx.moveTo(x - 5, y - 5);
      ctx.lineTo(x + 5, y + 5);
      ctx.stroke();
    });
  }
};
</script>

在上述代码中,我们添加了画布的宽度(canvasWidth)和高度(canvasHeight)以及单元格大小(cellSize)的定义。在更新坐标时,我们对机器人是否超出边界进行了判断,并只有在未超出边界的情况下才更新坐标。这样可以确保机器人不会走出画布范围。请根据实际情况调整画布大小和单元格大小的数值。

相关推荐
Penge6662 小时前
前端基础:html语义化
前端
用户30816998764852 小时前
同一个端口能被两个程序监听吗?TCP 11 组绑定实测
前端
deli0072 小时前
红绿灯配时实测:固定 60 秒 vs 自适应,2400 辆车差多少
前端
去伪存真2 小时前
井道无信号、满手黑机油,我们如何用 DeepSeek V4 打造不“犯浑”的电梯维保 Agent?
前端·agent
deli0072 小时前
60fps 为什么还是一顿一顿?帧时间曲线实测给你看
前端
时间的情敌2 小时前
Cesium 流动管线、管道动画、管线流向仿真,管网、油气、水利孪生高频需求
前端·交互·cesium
yuyuxun12 小时前
协同过滤的校园二手物品智能推荐系统的设计与实现 毕业设计-附源码40082
javascript·vue.js·spring boot·python·数据分析·django·课程设计
wangxiaoxuan2174 小时前
SLAM 的基本结构:前端、后端、回环与地图优化
前端·机器人·科沃斯八界
总要学点什么6 小时前
第105篇:三维特效-流动图片墙体效果——让箭头沿墙长滚,它俩竟是同一份代码
开发语言·javascript·ecmascript·gis·webgl·材质·cesium
Agent世界7 小时前
用 CDP 做发布自动化:四道机器闸门与产物验收
前端·javascript