怎么使用canvas创建动态topu,topu线带有动画效果的
时间: 2024-05-16 11:16:54 浏览: 12
要创建动态的topu,并且让topu线带有动画效果,可以使用 canvas 和 JavaScript。下面是一个简单的示例代码:
HTML:
```html
<canvas id="myCanvas"></canvas>
```
CSS:
```css
#myCanvas {
width: 100%;
height: 100vh;
}
```
JavaScript:
```javascript
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
const nodes = [];
const links = [];
// 创建节点
function createNode(x, y) {
nodes.push({ x, y });
}
// 创建链接
function createLink(source, target) {
links.push({ source, target });
}
// 绘制节点和链接
function draw() {
// 清空画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制链接
for (let i = 0; i < links.length; i++) {
const link = links[i];
const source = nodes[link.source];
const target = nodes[link.target];
// 计算链接的中心点
const cx = (source.x + target.x) / 2;
const cy = (source.y + target.y) / 2;
// 绘制链接线
ctx.beginPath();
ctx.moveTo(source.x, source.y);
ctx.lineTo(target.x, target.y);
ctx.strokeStyle = "#ccc";
ctx.stroke();
// 绘制链接中心点的圆形
ctx.beginPath();
ctx.arc(cx, cy, 5, 0, 2 * Math.PI);
ctx.fillStyle = "#fff";
ctx.fill();
// 绘制链接中心点的数字
ctx.fillStyle = "#000";
ctx.fillText(i + 1, cx, cy);
}
// 绘制节点
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i];
// 绘制节点圆形
ctx.beginPath();
ctx.arc(node.x, node.y, 20, 0, 2 * Math.PI);
ctx.fillStyle = "#fff";
ctx.fill();
// 绘制节点数字
ctx.fillStyle = "#000";
ctx.fillText(i + 1, node.x, node.y);
}
}
// 添加节点和链接
createNode(100, 100);
createNode(300, 100);
createNode(200, 300);
createLink(0, 1);
createLink(1, 2);
createLink(2, 0);
// 每一帧更新画布
function update() {
// 让节点随机移动
for (let i = 0; i < nodes.length; i++) {
nodes[i].x += Math.random() * 10 - 5;
nodes[i].y += Math.random() * 10 - 5;
}
// 更新画布
draw();
// 循环更新
requestAnimationFrame(update);
}
// 开始更新画布
update();
```
这段代码会创建一个包含三个节点和三条链接的topu,并且每一帧都会让节点随机移动,绘制出一个动态的topu。你可以根据自己的需求修改节点和链接的数量以及其他参数。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)