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

相关推荐
张一凡93几秒前
我用 Zustand 三年了,直到遇见 easy-model...
前端·javascript·react.js
张元清1 分钟前
React 拖拽:无需第三方库的完整方案
前端·javascript·面试
giszhc2 分钟前
geojson-to-kml (KML 格式转换工具)
前端
笨笨狗吞噬者2 分钟前
【uniapp】小程序支持分包存放微信自定义组件 wxcomponents
前端·微信小程序·uni-app
用户904706683574 分钟前
跟随系统暗黑模式动态更改已有的颜色
前端
giszhc5 分钟前
arcgis-to-geojson双向转换工具库
前端
Jeff_Wang6 分钟前
JavaScript 和 React Component 实现井字棋游戏
前端
新空20226 分钟前
vben5 ImageUpload 模块多图预览功能
前端
zhensherlock12 分钟前
Protocol Launcher 系列:Microsoft Edge 浏览器唤起的优雅方案
javascript·chrome·microsoft·typescript·edge·github·edge浏览器
Leo6553517 分钟前
动态 SQL(行+列) + 动态表头(前端+EasyPoi) = 完整透视报表系统
前端·sql·状态模式