canvas绘制马路和屏幕

 

<template>
  <div>
  <canvas ref="roadCanvas" width="550" height="150"></canvas>
  </div>
</template>

<script>
export default {
  data () {
    return {
      road: {
        width: 550,
        height: 200,
        color: "gray"
      },
      screens: [
        { x: 0, y: 0, width: 100, height: 40, text: "屏幕 1: 文字 1" },
        { x: 150, y: 0, width: 100, height: 40, text: "屏幕 2: 文字 2" },
        { x: 300, y: 0, width: 100, height: 40, text: "屏幕 3: 文字 3" },
        { x: 450, y: 0, width: 100, height: 40, text: "屏幕 4: 文字 4" }
      ],
      textSpeed: 20 // 文字滚动速度
    }
  },
  mounted() {
  this.updateScreen();
  },
  methods: {
     updateScreen() {
      const canvas = this.$refs.roadCanvas;
      const ctx = canvas.getContext("2d");

      // 渲染道路
      ctx.fillStyle = this.road.color;
      ctx.fillRect(0, 10, this.road.width, this.road.height);

      // 绘制白色斑马线
      ctx.fillStyle = "white";
      const lineWidth = 80; // 斑马线宽度
      const lineHeight = 10; // 斑马线高度
      const gap = 40; // 斑马线间隔

      let x = gap;

      while (x < canvas.width) {
        ctx.fillRect(x, 60, lineWidth, lineHeight);
        ctx.fillRect(x, 80, lineWidth, lineHeight);
        ctx.fillRect(x, 100, lineWidth, lineHeight);
        x += lineWidth + gap * 2;
      }



      this.screens.forEach(screen => {
        ctx.fillStyle = "black";
        ctx.fillRect(screen.x, screen.y, screen.width, screen.height);

        // 在屏幕上绘制滚动文字
        ctx.fillStyle = "white";
        ctx.font = "16px Arial";

        // 计算滚动位置
        const scrollPosition = (Date.now() * this.textSpeed / 1000) % (screen.text.length * 16);
        // console.log('123',scrollPosition)
        // 计算截断的位置,确保文字不会溢出屏幕
        const truncatePosition = Math.min(scrollPosition, screen.width);

          // 绘制滚动文字,通过截断位置来实现隐藏溢出部分
          ctx.fillText(
            screen.text.slice(0, truncatePosition / 10),
            screen.x + screen.width - truncatePosition,
            screen.y + 30
          );

      });

      requestAnimationFrame(this.updateScreen);
    },
  }
};
</script>

<style>
/* Add any custom styles here */
</style>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值