import { LengthMetricsUnit } from '@kit.ArkUI';
const WH: number = 256;
@Observed
class DemoLayer {
canvas: OffscreenCanvas;
context: OffscreenCanvasRenderingContext2D;
data: ImageData | undefined;
fp: number = 0;
constructor() {
this.canvas = new OffscreenCanvas(WH, WH, LengthMetricsUnit.PX);
this.context = this.canvas.getContext('2d', new RenderingContextSettings(false));
}
draw(): void {
this.context.fillStyle = '#5291FF';
this.context.fillRect(0, 0, WH, WH);
this.context.lineWidth = 5;
this.context.strokeStyle = '#F1F3F5';
this.context.beginPath();
this.context.ellipse(WH / 2, WH / 2, WH / 2, WH / 2, 0, 0, Math.PI * 2);
this.context.stroke();
}
flip(): void {
this.fp = 1 - this.fp;
}
}
在Index中是直接通过点击操作执行的putImageData,在DemoItem中则是通过@Watch的回调执行的putImageData。
@Entry
@Component
struct SyncCanvasContent {
message: string = '点击最大的方框进行绘图';
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(new RenderingContextSettings(false));
private context2: CanvasRenderingContext2D = new CanvasRenderingContext2D(new RenderingContextSettings(false));
@State layer: DemoLayer = new DemoLayer();
build() {
RelativeContainer() {
Text(this.message)
.id('DemoHelloWorld')
.fontSize(28)
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Bottom },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
});
DemoItem({ layer: this.layer })
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Top },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
});
Row({ space: 20 }) {
Canvas(this.context)
.width(200)
.height(200)
.borderWidth(2)
.onClick(() => this.onButtonClick());
Canvas(this.context2)
.width(100)
.height(100)
.borderWidth(2);
}
.alignRules({
center: { anchor: '__container__', align: VerticalAlign.Center },
middle: { anchor: '__container__', align: HorizontalAlign.Center }
});
}
.height('100%')
.width('100%');
}
onButtonClick(): void {
console.info('onButtonClick');
this.layer.draw();
this.layer.data = this.layer.context.getImageData(0, 0, WH, WH);
this.context.putImageData(this.layer.data, 0, 0);
// 此句用于证明layer中的绘画数据可以被多个context使用
this.context2.putImageData(this.layer.data, 0, 0);
}
}
@Component
struct DemoItem {
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(new RenderingContextSettings(false));
@ObjectLink @Watch('change') layer: DemoLayer;
change() {
this.context.putImageData(this.layer.data, 0, 0);
}
build() {
Stack() {
Canvas(this.context)
.width('100%')
.height('100%');
}
.width(60)
.height(60)
.borderWidth(2);
}
}