在我的 Angular 應用程式中,我已經做到了以下幾點。但是,圓圈??不會繪制在svg. 我做錯了什么,圓圈沒有顯示?
svg: any;
margin = 50;
width = 350 - (this.margin * 2);
height = 300 - (this.margin * 2);
ngOnInit(): void {
this.createSvg();
this.createCircle();
}
createSvg(): void {
this.svg = d3
.select("figure#zoom-pan")
.append("svg")
.attr("width", "100%")
.attr("height", "100%")
.append("g")
.attr("transform", "translate(" this.margin "," this.margin ")");
}
createCircle(): void {
this.svg
.append("circle")
.attr("cx", document.body.clientWidth / 2)
.attr("cy", document.body.clientHeight / 2)
.attr("r", 50)
.style("fill", "#B8DEE6")
}
ngAfterViewInit() {
let svg = d3
.select("svg")
.call(d3.zoom().on("zoom", (event) => {
svg.attr("transform", event.transform);
}))
.append("g");
}
我的html模板和css代碼非常簡單:
<h3 class="center">Zoom Pan</h3>
<figure id="zoom-pan" class="center"></figure>
<ng-content></ng-content>
.center {
display: flex;
justify-content: center;
}
figure#zoom-pan {
margin: 0;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
我只得到“Zoom Pan”和一個空白區域......我錯過了什么?
uj5u.com熱心網友回復:
使用 angular 時,我建議您放棄 D3 選擇器而只使用 angular。Angular 已經具有 DOM 操作標記,因此您無需使用 D3 來執行此操作。
// component
createCircle() {
this.circle = {
cx: document.body.clientWidth / 2,
cx: document.body.clientHeight / 2,
r: 50
}
}
// component template
<figure>
<svg
[height]="height (margin * 2)"
[width]="width (margin * 2)"
>
<g [attr.transform]="'translate(' margin ',' margin ')">
<circle *ngIf="circle"
[attr.cx]="circle.cx"
[attr.cy]="circle.cx"
[attr.r]="circle.r" />
</g>
</svg>
</figure>
uj5u.com熱心網友回復:
如果您沒有以像素為單位設定 svg 高度和寬度,根據我的經驗,您需要使用 viewBox。
this.svg = d3
.select("figure#zoom-pan")
.append("svg")
.attr("width", "100%")
.attr("height", "100%")
.attr("viewBox", "0 0 " this.width " " this.height)
uj5u.com熱心網友回復:
我制作了此代碼的一個作業示例,顯示了圓圈。首先它需要是一個類和一個角度組件。
在 stackblitz 查看作業示例
這是組件的打字稿:
import { Component, OnInit } from '@angular/core';
import * as d3 from 'd3';
@Component({
selector: "ng-content",
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
svg: any;
margin = 50;
width = 350 - this.margin * 2;
height = 300 - this.margin * 2;
ngOnInit(): void {
this.createSvg();
this.createCircle();
}
createSvg(): void {
this.svg = d3
.select("figure#zoom-pan")
.append("svg")
.attr("width", "100%")
.attr("height", "100%")
.append("g")
.attr("transform", "translate(" this.margin "," this.margin ")");
}
createCircle(): void {
this.svg
.append("circle")
.attr("cx", document.body.clientWidth / 2)
.attr("cy", document.body.clientHeight / 2)
.attr("r", 50)
.style("fill", "#B8DEE6");
}
ngAfterViewInit() {
let svg = d3
.select("svg")
.call(
d3.zoom().on("zoom", (event) => {
svg.attr("transform", event.transform);
})
)
.append("g");
}
}
和模板:
<h3 class="center">Zoom Pan</h3>
<figure id="zoom-pan" class="center"></figure>
我建議始終提供一個最小的作業示例。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/359428.html
標籤:javascript 有角的 打字稿 d3.js
上一篇:d3力圖中的同心圓
下一篇:新版本中的D3事件
