You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular Canvas文本横竖方向切换功能实现咨询

实现Canvas文本水平/垂直方向切换的方案

步骤1:扩展Shape数据结构

首先给你的Shape类型新增一个方向属性,用来存储用户选择的文本显示方向:

interface Shape {
  type: 'barcode' | 'text';
  x: number;
  y: number;
  w: number;
  h: number;
  text?: string;
  // 新增方向字段,默认设为水平
  orientation: 'horizontal' | 'vertical';
}

步骤2:添加方向选择UI

在Angular模板里,给每个文本项配上方向选择控件(比如下拉框),绑定到对应Shape的orientation属性:

<!-- 假设textShapes是你存储文本Shape的数组 -->
<div *ngFor="let item of textShapes">
  <label>文本方向:</label>
  <select [(ngModel)]="item.orientation">
    <option value="horizontal">水平</option>
    <option value="vertical">垂直</option>
  </select>
</div>

步骤3:修改drawText方法支持垂直绘制

Canvas没有原生垂直文本API,需要通过旋转画布实现。修改drawText方法,根据方向参数处理绘制逻辑:

private drawText(
  context: CanvasRenderingContext2D,
  text: string,
  x: number,
  y: number,
  w: number,
  h: number,
  orientation: 'horizontal' | 'vertical'
) {
  context.fillStyle = 'black';
  context.font = '8px Arial';

  if (orientation === 'vertical') {
    // 保存当前画布状态,避免影响其他图形绘制
    context.save();
    // 平移到文本区域中心,旋转90度后再平移回原位置
    context.translate(x + w/2, y + h/2);
    context.rotate(Math.PI / 2);
    context.translate(-(x + w/2), -(y + h/2));
    // 调整绘制坐标,适配垂直显示
    context.fillText(text, x, y + h);
    // 恢复画布原始状态
    context.restore();
  } else {
    // 原有水平绘制逻辑
    context.fillText(text, x, y);
  }
}

步骤4:更新绘制流程

修改startDrawing方法,把Shape的方向参数传递给drawText:

startDrawing(shapesToDraw: Shape[]) {
  console.log('inside startDrawing::');
  for (var i = 0; i < shapesToDraw.length; i++) {
    const shape = shapesToDraw[i];
    if (shape.type === 'barcode') {
      this.drawRectangle(this.context, shape.x, shape.y, shape.w, shape.h);
    } else if (shape.type === 'text') {
      this.drawText(
        this.context,
        shape.text!,
        shape.x,
        shape.y,
        shape.w,
        shape.h,
        shape.orientation
      );
    }
  }
}

可选优化:文本居中显示

如果需要文本在指定区域内居中,可添加文本对齐设置:

private drawText(...) {
  context.fillStyle = 'black';
  context.font = '8px Arial';

  if (orientation === 'vertical') {
    context.save();
    context.translate(x + w/2, y + h/2);
    context.rotate(Math.PI / 2);
    context.textAlign = 'center';
    context.textBaseline = 'middle';
    context.fillText(text, x + w/2, y + h/2);
    context.restore();
  } else {
    context.textAlign = 'left';
    context.textBaseline = 'top';
    context.fillText(text, x, y);
  }
}

内容的提问来源于stack exchange,提问作者ZAJ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 12:42:31