<svg>
元素
<svg>
是一種用于描述二維矢量圖形的 XML 格式,可以直接嵌入 HTML 文檔中。
<svg>
基本用法
<svg>
的幾種基本用法,包括圓形,正方形,三角形,直線 ,折線等
<body><svg width="180" height="100"><!-- 圓 --><circle cx="50" cy="50" r="40" storke-width="4" fill="yellow" /></svg><svg width="180" height="100"><!-- 正方形 --><rect x="10" y="10" width="80" height="80" fill="blue" /></svg><svg width="180" height="100"><!-- 橢圓 --><ellipse cx="50" cy="50" rx="30" ry="20" fill="green" /></svg><svg width="180" height="100"><!-- 直線 --><line x1="10" y1="10" x2="90" y2="90" stroke="black" /></svg><svg width="180" height="100"><!-- 三角形 --><polygon points="50,10 90,90 10,90" fill="purple" /></svg><svg width="300" height="200"><!-- 星型 --><polygon points="100,10,40,198,190,78,10,78,160,198"style="fill: lime; stroke: plum; stroke-width: 5; fill-rule: evenodd;"/></svg><svg width="180" height="100"><!-- 折線 --><polyline points="10,10 30,30 50,10 70,30 90,10" fill="none" stroke="black" /></svg>
</body>
<svg>
也可以使用CSS屬性
<svg width="100" height="100"><style>circle {fill: red;stroke: black;stroke-width: 3;}</style><circle cx="50" cy="50" r="40" /></svg>
<svg>
高級特性
<svg>
漸變
<svg width="180" height="100"><!-- 漸變 --><defs><linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%"><stop offset="0%" style="stop-color:rgb(255,255,0);stop-opacity:1" /><stop offset="100%" style="stop-color:rgb(255,0,0);stop-opacity:1" /></linearGradient></defs><rect x="10" y="10" width="80" height="80" fill="url(#grad1)" />
</svg>
<svg>
濾鏡
<svg width="180" height="100"><!-- 濾鏡 --><defs><filter id="blur"><feGaussianBlur in="SourceGraphic" stdDeviation="5" /></filter></defs><rect x="10" y="10" width="80" height="80" fill="blue" filter="url(#blur)" />
</svg>
<svg>
動畫
<svg width="180" height="100"><!-- 動畫 --><circle cx="50" cy="50" r="20" fill="red"><animate attributeName="cx" from="50" to="150" dur="3s" repeatCount="indefinite" /></circle>
</svg>
<svg>
元素和<canvas>
元素
SVG(Scalable Vector Graphics)是一種基于XML的矢量圖形格式,每個圖形元素都是DOM樹的一部分。Canvas則是一個通過JavaScript API進行像素級繪制的位圖畫布,提供更底層的繪圖控制。
核心技術區別
圖形類型:
<svg>
使用矢量圖形描述,由數學方程定義形狀
<canvas>
生成位圖圖像,由像素矩陣構
DOM集成:
<svg>
元素完全融入DOM,可單獨操作和綁定事件
<canvas>
作為整體DOM元素存在,內部圖形無獨立DOM表示
渲染機制:
<svg>
采用保留模式渲染,自動管理圖形狀
<canvas>
使用立即模式,開發者需手動控制繪制過程
交互能力:
<svg>
原生支持圖形級事件處理
<canvas>
需手動實現點擊檢測等交互邏輯
性能特征對比
靜態內容:
<svg>
在渲染少量復雜圖形時效率更高
<canvas>
更適合處理大量動態圖形元素
動畫性能:
<svg>
動畫受DOM操作限制
<canvas>
可通過清除重繪實現高效動畫
內存占用:
<svg>
內存消耗與圖形復雜度相關
<canvas>
內存占用由畫布分辨率決定
適用場景分析
<svg>
優勢場景:
需要無限縮放的高質量圖形
圖形需要單獨交互和樣式控制
對可訪問性和SEO有要求的項目
<canvas>
優勢場景:
數據可視化和大規模圖形渲染
游戲開發和實時圖像處理
需要像素級操作的應用