1. 折线图
<svg width="400" height="200">
<!-- X轴 -->
<line x1="50" y1="150" x2="350" y2="150" stroke="black" />
<!-- Y轴 -->
<line x1="50" y1="150" x2="50" y2="50" stroke="black" />
<!-- 折线 -->
<polyline points="50,150 100,100 150,120 200,80 250,130 300,70 350,100" fill="none" stroke="blue" />
</svg>
解释:
- 使用
<line>
元素绘制X轴和Y轴。 - 使用
<polyline>
元素绘制折线,通过points
属性设置折线的坐标点。
2. 曲线图
<svg width="400" height="200">
<!-- X轴 -->
<line x1="50" y1="150" x2="350" y2="150" stroke="black" />
<!-- Y轴 -->
<line x1="50" y1="150" x2="50" y2="50" stroke="black" />
<!-- 曲线 -->
<path d="M50,150 C100,100 200,100 300,150 C350,200 350,200 350,150" fill="none" stroke="red" />
</svg>
解释:
- 使用
<path>
元素绘制贝塞尔曲线,通过d
属性设置曲线路径。
3. 柱状图
<svg width="400" height="200">
<!-- X轴 -->
<line x1="50" y1="150" x2="350" y2="150" stroke="black" />
<!-- Y轴 -->
<line x1="50" y1="150" x2="50" y2="50" stroke="black" />
<!-- 柱子 -->
<rect x="75" y="100" width="50" height="50" fill="blue" />
<rect x="150" y="80" width="50" height="70" fill="green" />
<rect x="225" y="120" width="50" height="30" fill="red" />
</svg>
解释:
- 使用
<rect>
元素绘制柱子,通过x
、y
、width
和height
属性设置柱子的位置和大小。
4. 饼图
<svg width="400" height="200">
<!-- 饼图 -->
<circle cx="100" cy="100" r="80" fill="blue" />
<circle cx="100" cy="100" r="80" fill="none" stroke="white" stroke-width="40" stroke-dasharray="50 100" />
</svg>
解释:
- 使用两个
<circle>
元素实现饼图,一个填充颜色,一个作为边框并设置stroke-dasharray
属性实现饼图的分割效果。
5. 地图
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Interactive Map</title>
<style>
.map {
width: 600px;
height: 400px;
border: 1px solid #ccc;
}
.region {
fill: #eee;
stroke: #666;
stroke-width: 1px;
cursor: pointer;
}
.region:hover {
fill: #f0f0f0;
}
</style>
</head>
<body>
<svg class="map" viewBox="0 0 600 400" xmlns="http://www.w3.org/2000/svg">
<!-- 地图区域 -->
<path class="region" d="M100,200 L200,100 L300,200 L200,300 Z" id="region1" />
<path class="region" d="M400,200 L500,100 L600,200 L500,300 Z" id="region2" />
<!-- 添加交互效果 -->
<script>
const regions = document.querySelectorAll('.region');
regions.forEach(region => {
region.addEventListener('click', () => {
alert(`You clicked region ${region.id}`);
});
});
</script>
</svg>
</body>
</html>
解释:
- 使用
<path>
元素绘制地图区域,通过d
属性设置路径。 - 使用CSS样式控制地图区域的填充色、边框色和鼠标样式。
- 使用JavaScript监听地图区域的点击事件,并添加交互效果。
这个示例中绘制了两个简单的地图区域,点击地图区域会弹出提示框显示区域的ID。你可以根据实际需求继续完善地图的绘制和交互功能,例如添加更多区域、显示区域信息等。