1
0
mirror of https://gitee.com/coder-xiaomo/algorithm-visualization synced 2025-09-06 21:01:39 +08:00
Code Issues Projects Releases Wiki Activity GitHub Gitee
Files
algorithm-visualization/src/assets/js/index.js

266 lines
8.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 全局变量
var settings = {
container: d3.select("#container"),
debugMode: false,
outerSize: { // 不带单位
width: 800,
height: 450
},
innerSize: { // 不带单位,通过 outerSize 和 margin 计算得到
width: null,
height: null
},
width: null, // 带单位,通过 outerSize 计算得到
height: null, // 带单位,通过 outerSize 计算得到
margin: { // 不带单位
top: 180,
right: 20,
bottom: 180,
left: 20
},
oneUnit: { // 不带单位,通过 innerSize 计算得到
transverse: null, // 横向单位长度 ( innerSize 的 1% )
longitudinal: null // 纵向单位长度 ( innerSize 的 1% )
},
colorMap: {
"background": "#ddd",
"stroke": "#e02433", // 边框颜色
"fill": "#ffa4ab", // 填充颜色
"fill_focus": "#ee737d", // 填充颜色
"text": "#8a0f19", // 文本颜色
"text_focus": "white", // 文本颜色
"red": "#f00",
"green": "#0f0",
},
animation: {
getConf: function () { // gsap动画传入默认设置
return {
duration: 0.3, // 单位是秒
ease: "sine.inOut",
delay: 0,
yoyo: true,
}
}
},
console: {
maxLine: 30,
consoleList: [], // 输出列表的数组,不要修改
}
}
settings.width = settings.outerSize.width + "px";
settings.height = settings.outerSize.height + "px";
settings.innerSize.width = settings.outerSize.width - settings.margin.left - settings.margin.right;
settings.innerSize.height = settings.outerSize.height - settings.margin.top - settings.margin.bottom;
settings.oneUnit.transverse = settings.innerSize.width / 100;
settings.oneUnit.longitudinal = settings.innerSize.height / 100;
console.log("settings", settings)
// 绘制数组
function initArray(elementId, listData) {
let fragment = shape.getLinkedListFragment(elementId, listData, {
x: 100,
y: 100,
width: "100px",
height: "100px",
})
console.log(fragment)
workSpace.primaryCanvas.html("")
workSpace.primaryCanvas.node().appendChild(fragment)
document.getElementById(elementId).customAttr = fragment.customAttr
}
// 初始化
var workSpace = new WorkSpace(settings)
var shape = new Shape(workSpace)
var animation = new VectorAnimation(workSpace)
var listData // = [47, 11, 50, 13, 16, 49, 8, 9, 38, 27, 20] // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
function updateListDataInput() {
document.getElementById("array-input").value = listData.join("")
}
function updateListDataArray(elementId, { doNotAlert = false }) {
var val = document.getElementById("array-input").value
try {
var preList = val.replaceAll("", ",").split(",")
listData = []
preList.forEach(element => {
if (element.trim() === "" || isNaN(element))
return
listData.push(Number(element))
});
// console.log(preList, listData)
initArray(elementId, listData)
} catch (err) {
console.log(err)
if (!doNotAlert)
alert("输入不正确,请检查!")
return false
}
return true
}
function randomListDataArray(elementId) {
function getRandom(length) {
return Math.floor(Math.random() * length); // 可均衡获取 0 到 length-1 的随机整数。
}
// 获取一个 6 - 12 以内的随机数
var len = 6 + getRandom(13 - 6)
listData = []
for (let i = 0; i < len; i++) {
listData.push(getRandom(51))
}
updateListDataInput()
updateListDataArray(elementId, { doNotAlert: false })
}
// 网页加载完毕初始化事件
function initialize() {
var elementId = "array-sort-algorithm"
let controlDiv = document.getElementById("control-div")
var sortClassList = getSortClassList();
console.log(sortClassList);
var DOMFragment = document.createDocumentFragment()
for (let i = 0; i < sortClassList.length; i++) {
const sortClass = new sortClassList[i](animation)
const sortClassInfo = sortClass.info()
// 跳过未完成的算法
if (!sortClassInfo['available'])
continue
let ctrlBtn = document.createElement("button")
ctrlBtn.innerHTML = sortClassInfo['name']
ctrlBtn.onclick = function () {
// 点击排序算法按钮
if (!updateListDataArray(elementId, { doNotAlert: false }))
return
// 隐藏一些东西,显示一些东西
controlDiv.style.display = 'none'
d3.select("#console-div")
.style("display", "")
d3.select("#console-current-algorithm")
.style("text-align", "center")
.html(sortClassInfo['name'])
sortClass.doSortWithAnimation(elementId)
}
DOMFragment.appendChild(ctrlBtn)
}
controlDiv.appendChild(DOMFragment)
// 生成一个随机数组
randomListDataArray(elementId)
// 显示 siderbar
d3.select("#sidebar").style("display", "")
}
initialize()
// 输出
function consoleLog(data) {
let consoleList = settings.console.consoleList
if (data) {
consoleList.push(data)
if (consoleList.length > settings.console.maxLine + 1) {
consoleList.shift()
consoleList[0] = "<small>更早的记录已经被丢掉啦</small>"
}
}
let consoleContainer = document.getElementById("console-logs")
consoleContainer.innerHTML = consoleList.join("<br>")
consoleContainer.scrollTop = container.scrollHeight
}
function consoleClear() {
settings.console.consoleList = []
consoleLog()
}
// 展示当前数组
function displayCurrentArray(array) {
let dom = []
for (let index = 0; index < array.length; index++) {
const element = array[index];
dom.push(`<span style="margin: 0 4px;">${element.toString()}</span>`)
}
document.getElementById("console-current-array").innerHTML = "当前数组:" + dom.join("&nbsp;")
}
// 测试
// shape.rectangle("ele1", {
// x: 10,
// y: 10,
// width: "20%",
// height: "30%",
// fillColor: "blue",
// strokeColor: "red"
// }).style("stroke-width", "10px")
// shape.circle("ele2", {
// x: 200,
// y: 50,
// radius: "20px",
// fillColor: "green",
// strokeColor: "red"
// })
// shape.text("ele3", {
// x: 200,
// y: 150,
// text: "文本",
// fillColor: "red"
// })
// shape.line("ele4", {
// x1: 100,
// y1: 100,
// x2: 200,
// y2: 200,
// strokeColor: "red"
// })
// 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([settings.innerSize.height, 0])
// }
// var line_generator = d3.line()
// .x(function (d, i) { return scale.x(i); })
// .y(function (d, i) { return scale.y(d); })
// // .curve(d3.curveBasis)
// // .curve(d3.curveCardinal)
// shape.path("ele5", line_generator(data), {
// fillColor: "none",
// strokeColor: "red"
// })
// 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("ele7", 300, 200, "20px", "20px", "文本")