HarmonyOS鸿蒙Next基于Canvas实现选座功能示例代码

HarmonyOS鸿蒙Next基于Canvas实现选座功能示例代码

介绍

本示例基于Canvas组件,构建了一个有关电影院购票选座场景,实现了选座/退座功能。

基于Canvas实现选座功能源码链接

效果预览

图片名称

使用说明

  1. 应用启动时展示一个10×10的正方形,每个小正方形相当于一个座位;
  2. 点击任何一个正方形,该正方形变成黄色,表示该座位被选中,座位号记录下来,选中座位数量增加;
  3. 点击选中按钮,弹出对话框,显示选中的座位,提示你是否确认支付,如果确认,选中的座位就会 变成红色,如果取消,对话框消失。之后还能正常选择;
  4. 如果点击清空,所有选中的和确认的座位都变成灰色,恢复到初始状态。

实现思路

  1. 使用canvas组件画图,开始进入页面时,画一个10×10的正方形,同时使用seats记录座位是否被选中,默认值0表示没选中。
  2. 定义drawRect函数,用来画图,id为0画笔是灰色,id为1是黄色,id是2表示红色,同时给canvas画布绑定点击事件,算出点击的座位号,然后把该座位变成黄色,改变seats对应的座位号变成1,记录选中的座位号。
  3. 点击选中座位按钮,弹出对话框。
  4. 点击选中座位按钮,弹出对话框。
  5. 点击清空,所有的座位都变成灰色,同时记录也清空。

更多关于HarmonyOS鸿蒙Next基于Canvas实现选座功能示例代码的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于HarmonyOS鸿蒙Next基于Canvas实现选座功能示例代码的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


HarmonyOS鸿蒙Next中,Canvas是用于绘制2D图形的组件,可以通过它实现自定义的UI效果,例如选座功能。以下是一个基于Canvas实现选座功能的示例代码:

import { Canvas, CanvasRenderingContext2D, Rect } from '@ohos.graphics';

class SeatSelection {
  private canvas: Canvas;
  private ctx: CanvasRenderingContext2D;
  private seats: Array<Array<boolean>>;
  private seatSize: number = 40;
  private padding: number = 10;

  constructor(canvasId: string, rows: number, cols: number) {
    this.canvas = new Canvas(canvasId);
    this.ctx = this.canvas.getContext('2d');
    this.seats = new Array(rows).fill(false).map(() => new Array(cols).fill(false));
  }

  drawSeats() {
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
    for (let i = 0; i < this.seats.length; i++) {
      for (let j = 0; j < this.seats[i].length; j++) {
        const x = j * (this.seatSize + this.padding);
        const y = i * (this.seatSize + this.padding);
        this.ctx.fillStyle = this.seats[i][j] ? 'green' : 'gray';
        this.ctx.fillRect(x, y, this.seatSize, this.seatSize);
      }
    }
  }

  handleClick(x: number, y: number) {
    const col = Math.floor(x / (this.seatSize + this.padding));
    const row = Math.floor(y / (this.seatSize + this.padding));
    if (row >= 0 && row < this.seats.length && col >= 0 && col < this.seats[row].length) {
      this.seats[row][col] = !this.seats[row][col];
      this.drawSeats();
    }
  }
}

// 使用示例
const seatSelection = new SeatSelection('myCanvas', 5, 10);
seatSelection.drawSeats();

// 绑定点击事件
const canvasElement = document.getElementById('myCanvas');
canvasElement.addEventListener('click', (event) => {
  const rect = canvasElement.getBoundingClientRect();
  const x = event.clientX - rect.left;
  const y = event.clientY - rect.top;
  seatSelection.handleClick(x, y);
});

这段代码定义了一个SeatSelection类,用于管理选座功能。drawSeats方法绘制座位,handleClick方法处理点击事件,切换座位状态。通过Canvas的2D上下文,可以实现简单的交互式选座功能。

回到顶部