Tất cả trình duyệt hiện đại hỗ trợ SVG. Có thể tạo và thao tác SVG hoàn toàn bằng JavaScript DOM API.
Tạo SVG element cơ bản
const svgNS = "https://www.w3.org/2000/svg";
const svg = document.createElementNS(svgNS, "svg");
svg.setAttribute("width", "100");
svg.setAttribute("height", "100");
// Tạo hình tròn
const circle = document.createElementNS(svgNS, "circle");
circle.setAttributeNS(null, "cx", 50);
circle.setAttributeNS(null, "cy", 50);
circle.setAttributeNS(null, "r", 40);
circle.setAttributeNS(null, "fill", "yellow");
circle.setAttributeNS(null, "stroke", "orange");
circle.setAttributeNS(null, "stroke-width", "2");
svg.appendChild(circle);
document.body.appendChild(svg);
Các phương thức quan trọng
document.createElementNS(namespace, tagName)– Bắt buộc dùng namespace SVG.setAttributeNS(null, name, value)– Đặt attribute (null namespace cho attribute thông thường).getAttributeNS(null, name)– Đọc attribute.
Ví dụ hoàn chỉnh: Tròn theo chuột
<!DOCTYPE html>
<html>
<body>
<svg id="svgCanvas" width="400" height="300" style="border:1px solid #ccc"></svg>
<script>
const svg = document.getElementById('svgCanvas');
const svgNS = "https://www.w3.org/2000/svg";
svg.addEventListener('mousemove', e => {
// Xóa tròn cũ
while (svg.firstChild) svg.removeChild(svg.firstChild);
// Tạo tròn mới tại vị trí chuột
const circle = document.createElementNS(svgNS, "circle");
circle.setAttributeNS(null, "cx", e.offsetX);
circle.setAttributeNS(null, "cy", e.offsetY);
circle.setAttributeNS(null, "r", 20);
circle.setAttributeNS(null, "fill", "hsl(" + (e.offsetX % 360) + ", 70%, 60%)");
svg.appendChild(circle);
});
</script>
</body>
</html>
Thư viện SVG khuyến nghị
- D3.js – Data-driven documents, mạnh cho visualization.
- Snap.svg – jQuery cho SVG (animation, path manipulation).
- SVG.js – Lightweight, fluent API.
- Paper.js – Vector graphics scripting.