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)的定义。在更新坐标时,我们对机器人是否超出边界进行了判断,并只有在未超出边界的情况下才更新坐标。这样可以确保机器人不会走出画布范围。请根据实际情况调整画布大小和单元格大小的数值。

相关推荐
掘金安东尼2 分钟前
前端周刊第421期(2025年7月1日–7月6日)
前端·面试·github
摸鱼仙人~5 分钟前
深入理解 classnames:React 动态类名管理的最佳实践
前端·react.js·前端框架
未来之窗软件服务7 分钟前
chrome webdrive异常处理-session not created falled opening key——仙盟创梦IDE
前端·人工智能·chrome·仙盟创梦ide·东方仙盟·数据调式
kymjs张涛7 分钟前
零一开源|前沿技术周报 #6
前端·ios·harmonyos
玲小珑11 分钟前
Next.js 教程系列(十)getStaticPaths 与动态路由的静态生成
前端·next.js
天天鸭17 分钟前
写个vite插件自动处理系统权限,降低99%重复工作
前端·javascript·vite
蓝婷儿21 分钟前
每天一个前端小知识 Day 23 - PWA 渐进式 Web 应用开发
前端
无奈何杨31 分钟前
CoolGuard风控中新增移动距离和移动速度指标
前端·后端
恋猫de小郭38 分钟前
Google I/O Extended :2025 Flutter 的现状与未来
android·前端·flutter
江城开朗的豌豆42 分钟前
Vue-router方法大全:让页面跳转随心所欲!
前端·javascript·vue.js