根据提供的json动态生成多个画布区域

dsn*_*snr 5 html5-canvas angular

我正在使用angular2和html5 canvas。基于提供的json,我想在其中包含画布区域的情况下创建多个div。

这是用画布区域生成我的div的方式(HTML CODE)

<div class="masterpage" *ngFor="let x of masterPages" draggable [dragScope]="'masterpage'" [dragData]="x">
    <canvas #myCanvas width="105" height="149" style="background:lightgray;"></canvas>
</div>
Run Code Online (Sandbox Code Playgroud)

.ts代码

ngAfterViewInit() {
    let canvas = this.myCanvas.nativeElement;
    this.context = canvas.getContext("2d");
    this.tick(this.masterPages);
}

tick(masterPages) {
    var ctx = this.context;
    ctx.clearRect(0, 0, 150, 150);
    for (let j = 0; j < this.masterPages[this.count].areas.length; j++) {
        ctx.fillStyle = this.masterPages[this.count].areas[j].type;
        ctx.fillRect(masterPages[this.count].areas[j].x / 2, masterPages[this.count].areas[j].y / 2, masterPages[this.count].areas[j].width / 2, masterPages[this.count].areas[j].height / 2);
    }
    this.count = this.count + 1;
}
Run Code Online (Sandbox Code Playgroud)

以下是我的json

masterPages = [{
        areas: [
            {
                type: "FlowArea",
                width: "183.0",
                x: "12.0",
                y: "40.0",
                id: "FAR.1",
                height: "237.0"
            },
            {
                type: "StaticArea",
                width: "210.0",
                x: "0.0",
                y: "7.0",
                id: "SAR.2",
                height: "25.0"
            },
            {
                type: "StaticArea",
                width: "210.0",
                x: "0.0",
                y: "282.0",
                id: "SAR.1",
                height: "15.0"
            },
            {
                type: "StaticArea",
                width: "2.0",
                x: "6.0",
                y: "26.0",
                id: "SAR.3",
                height: "256.0"
            }
        ]
    },
    {
        areas: [
            {
                type: "FlowArea",
                width: "183.0",
                x: "12.0",
                y: "13.25",
                id: "FAR.1",
                height: "265.0"
            },
            {
                type: "StaticArea",
                width: "210.0",
                x: "0.0",
                y: "282.0",
                id: "SAR.1",
                height: "15.0"
            }
        ]
    }
    ];
Run Code Online (Sandbox Code Playgroud)

根据json,两个画布都应具有某些形状,但在我的情况下,第二个画布将变空

Men*_*ini 3

尝试使用 @ViewChildren 而不是 @ViewChild 并使用迭代每个画布

let canvas = this.myCanvas.toArray()[i].nativeElement;
Run Code Online (Sandbox Code Playgroud)

那么谁将有权访问动态创建的每个画布区域。