在CanvasRenderingContext2D 进行镂空操作 HarmonyOS 鸿蒙Next

在CanvasRenderingContext2D 进行镂空操作 HarmonyOS 鸿蒙Next 在CanvasRenderingContext2D 进行镂空操作,重叠的部分会变成透明

2 回复

可以参考如下demo:

import { display } from '@kit.ArkUI'

@Entry
@Component
struct ClearRect {
  private settings: RenderingContextSettings = new RenderingContextSettings(true)
  private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
  build() {
    Stack({alignContent:Alignment.TopStart}) {
      Canvas(this.context)
        .width('100%')
        .height('100%')
        .onReady(() =>{
          this.context.globalCompositeOperation = 'xor'
          this.context.beginPath();
          this.context.rect(0,0,px2vp(display.getDefaultDisplaySync().width),px2vp(display.getDefaultDisplaySync().height)-40);
          this.context.closePath();
          this.context.fillStyle = '#000000';
          this.context.fillStyle = '#6000000';
          this.context.fill();
          this.context.beginPath();
          this.context.rect(100,100,200,200);
          this.context.closePath();
          this.context.fillStyle = '#000000';
          this.context.fill();
        })
        .opacity(0.6)
    }
    .backgroundColor(Color.Yellow)
    .width('100%')
    .height('100%')
  }
}

更多关于在CanvasRenderingContext2D 进行镂空操作 HarmonyOS 鸿蒙Next的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS的CanvasRenderingContext2D中进行镂空操作,可以使用globalCompositeOperation属性。该属性允许你设置如何将新绘制的图形与现有的图形进行组合。要实现镂空效果,可以将globalCompositeOperation设置为destination-out,这样新绘制的图形会从现有的图形中“挖空”。

具体步骤如下:

  1. 创建一个Canvas对象并获取其上下文。
  2. 使用fillRect等方法绘制一个背景图形。
  3. 设置globalCompositeOperationdestination-out
  4. 在需要镂空的位置绘制一个新的图形,这个图形会从背景图形中“挖空”。

示例代码如下:

const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');

// 绘制背景
ctx.fillStyle = 'blue';
ctx.fillRect(0, 0, 200, 200);

// 设置镂空模式
ctx.globalCompositeOperation = 'destination-out';

// 绘制镂空图形
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2);
ctx.fill();

// 恢复默认模式
ctx.globalCompositeOperation = 'source-over';

在这个示例中,首先绘制了一个蓝色的矩形背景,然后通过设置globalCompositeOperationdestination-out,在矩形的中心绘制了一个圆形,圆形区域被“挖空”,最终形成了镂空效果。

回到顶部