js实现插入图形
使用Canvas绘制图形
Canvas是HTML5提供的绘图API,通过JavaScript可以动态绘制各种图形。创建一个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, 100);
</script>
使用SVG插入图形
SVG是可缩放矢量图形,可以直接嵌入HTML中。通过JavaScript可以动态创建和修改SVG元素。
<svg id="mySvg" width="200" height="200"></svg>
<script>
const svg = document.getElementById('mySvg');
const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
rect.setAttribute('x', '10');
rect.setAttribute('y', '10');
rect.setAttribute('width', '100');
rect.setAttribute('height', '100');
rect.setAttribute('fill', 'blue');
svg.appendChild(rect);
</script>
使用CSS绘制简单图形
通过CSS的border、border-radius等属性可以创建简单的图形,如圆形、三角形等。
<div id="circle"></div>
<style>
#circle {
width: 100px;
height: 100px;
background-color: green;
border-radius: 50%;
}
</style>
使用第三方库绘制复杂图形
对于更复杂的图形需求,可以使用第三方库如D3.js、Three.js等。这些库提供了丰富的图形绘制功能。
<script src="https://d3js.org/d3.v7.min.js"></script>
<div id="chart"></div>
<script>
const svg = d3.select('#chart')
.append('svg')
.attr('width', 200)
.attr('height', 200);
svg.append('circle')
.attr('cx', 100)
.attr('cy', 100)
.attr('r', 50)
.attr('fill', 'purple');
</script>
动态修改图形属性
通过JavaScript可以动态修改图形的属性,如位置、大小、颜色等,实现交互效果。

<canvas id="dynamicCanvas" width="200" height="200"></canvas>
<script>
const dynamicCanvas = document.getElementById('dynamicCanvas');
const dynamicCtx = dynamicCanvas.getContext('2d');
let x = 10;
function draw() {
dynamicCtx.clearRect(0, 0, 200, 200);
dynamicCtx.fillStyle = 'orange';
dynamicCtx.fillRect(x, 10, 50, 50);
x += 1;
if (x < 150) {
requestAnimationFrame(draw);
}
}
draw();
</script>






