1
0
mirror of https://gitee.com/coder-xiaomo/algorithm-visualization synced 2025-01-10 11:48:18 +08:00
Code Issues Projects Releases Wiki Activity GitHub Gitee

添加坐标轴实现

This commit is contained in:
程序员小墨 2022-05-16 01:23:52 +08:00
parent a4bc48c805
commit 82ccecddaa
2 changed files with 31 additions and 6 deletions

View File

@ -48,6 +48,12 @@ class Shape {
}
addShape(shape, id) {
var settings = this.workSpace.settings
return workSpace.primaryCanvas.append(shape)
.style("transform", `translate(${settings.margin.left}px, ${settings.margin.top}px)`)
.attr("id", id)
}
addShape_NoTransform(shape, id) {
return workSpace.primaryCanvas.append(shape)
.attr("id", id)
}
@ -93,13 +99,20 @@ class Shape {
}
// 添加路径
path(id,d, { fillColor = "white", strokeColor = "black" }) {
path(id, d, { fillColor = "white", strokeColor = "black" }) {
return this.addShape("path", id)
.attr("d", d)
.style("fill", fillColor)
.style("stroke", strokeColor)
}
// 添加坐标轴
axis(id, { transform, axis }) {
return this.addShape_NoTransform("g", id)
.attr("transform", transform)
.call(axis)
}
// 添加一个链表节点
addNode(id, x, y, width, height, text) {
var primaryCanvas = workSpace.primaryCanvas

View File

@ -12,7 +12,7 @@ var settings = {
},
width: null, // 带单位,通过 outerSize 计算得到
height: null, // 带单位,通过 outerSize 计算得到
margin: {
margin: { // 不带单位
top: 20,
right: 20,
bottom: 20,
@ -75,14 +75,17 @@ shape.line("ele4", {
strokeColor: "red"
})
var data = [1, 3, 5, 7, 3, 5, 9]
var data = []
for (let i = 0; i < 20; i++) // 生成随机数
data.push(Math.ceil(Math.random() * 10))
var scale = {
x: d3.scaleLinear()
.domain([0, data.length - 1])
.range([0, settings.innerSize.width]),
y: d3.scaleLinear()
.domain([0, d3.max(data)])
.range([0, settings.innerSize.height])
.range([settings.innerSize.height, 0])
}
var line_generator = d3.line()
.x(function (d, i) { return scale.x(i); })
@ -94,12 +97,21 @@ shape.path("ele5", line_generator(data), {
fillColor: "none",
strokeColor: "red"
})
shape.path("ele5", line_generator.curve(d3.curveCardinal)(data), {
shape.path("ele6", line_generator.curve(d3.curveCardinal)(data), {
fillColor: "none",
strokeColor: "green"
})
// shape.addShape("g", "axisX").attr("transform", `translate(${settings.margin.left}, ${settings.outerSize.height - settings.margin.bottom})`)//.attr("fill", "red")
shape.axis("axisX", {
transform: `translate(${settings.margin.left}, ${settings.outerSize.height - settings.margin.bottom})`,
axis: d3.axisBottom(scale.x)
})
shape.axis("axisY", {
transform: `translate(${settings.margin.left}, ${settings.margin.top})`,
axis: d3.axisLeft(scale.y)
})
shape.addNode("ele5", 300, 200, "20px", "20px", "文本")
shape.addNode("ele7", 300, 200, "20px", "20px", "文本")
// // 添加 g 元素
// primaryCanvas.append("g")