js实现插入图形
使用Canvas绘制图形
在HTML中创建Canvas元素,通过JavaScript的Canvas API绘制图形。Canvas适合动态、复杂的图形绘制,如游戏或数据可视化。
<canvas id="myCanvas" width="200" height="200"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 绘制矩形
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 100, 50);
// 绘制圆形
ctx.beginPath();
ctx.arc(150, 75, 30, 0, Math.PI * 2);
ctx.fillStyle = 'blue';
ctx.fill();
</script>
使用SVG插入矢量图形
SVG是XML-based的矢量图形格式,可直接嵌入HTML或通过JavaScript动态创建。适合需要缩放的图形。

<svg id="mySvg" width="200" height="200">
<rect x="10" y="10" width="100" height="50" fill="red"/>
<circle cx="150" cy="75" r="30" fill="blue"/>
</svg>
<script>
const svg = document.getElementById('mySvg');
const newCircle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
newCircle.setAttribute("cx", "50");
newCircle.setAttribute("cy", "150");
newCircle.setAttribute("r", "20");
newCircle.setAttribute("fill", "green");
svg.appendChild(newCircle);
</script>
使用CSS绘制简单图形
通过CSS的border、border-radius等属性可以创建简单图形,无需JavaScript。

<div class="rectangle"></div>
<div class="circle"></div>
<style>
.rectangle {
width: 100px;
height: 50px;
background-color: red;
}
.circle {
width: 60px;
height: 60px;
background-color: blue;
border-radius: 50%;
}
</style>
使用第三方库(如D3.js、Three.js)
对于复杂可视化需求,可使用专业图形库:
- D3.js适合数据可视化
- Three.js适合3D图形
<script src="https://d3js.org/d3.v7.min.js"></script>
<script>
d3.select("body").append("svg")
.attr("width", 200)
.attr("height", 200)
.append("rect")
.attr("x", 10)
.attr("y", 10)
.attr("width", 100)
.attr("height", 50)
.attr("fill", "purple");
</script>
动态加载外部图像文件
通过Image对象或直接修改img标签的src属性来插入外部图形文件。
<img id="dynamicImage" />
<script>
const img = new Image();
img.src = 'path/to/image.png';
img.onload = function() {
document.getElementById('dynamicImage').src = this.src;
};
</script>






