本章节提供 SVG DOM API 的快速参考,包括常用属性、方法和事件。
SVG 根元素的接口。
const svg = document.querySelector('svg');常用属性:
width: SVG 宽度height: SVG 高度viewBox: 视图框常用方法:
createSVGPoint(): 创建 SVGPoint 点对象(常用于坐标转换)createSVGRect(): 创建 SVGRect 矩形几何对象(注意:并非 <rect> 图形元素)getScreenCTM(): 获取屏幕变换矩阵所有图形元素的基类。
const rect = document.querySelector('rect');常用属性:
transform: 变换列表classList: 类列表常用方法:
getBBox(): 获取边界框getCTM(): 获取当前变换矩阵getScreenCTM(): 获取屏幕变换矩阵获取元素的边界框:
const bbox = element.getBBox();
console.log(bbox.x, bbox.y, bbox.width, bbox.height);获取当前变换矩阵:
const ctm = element.getCTM();
console.log(ctm.a, ctm.b, ctm.c, ctm.d, ctm.e, ctm.f);获取屏幕坐标变换矩阵:
const screenCTM = element.getScreenCTM();// 使用 getAttribute
const fill = element.getAttribute('fill');
// 使用 SVG DOM 属性
const width = element.width.baseVal.value;// 使用 setAttribute
element.setAttribute('fill', 'red');
// 使用 SVG DOM 属性
element.width.baseVal.value = 100;element.removeAttribute('fill');element.addEventListener('click', (e) => {
console.log('Clicked', e.target);
});
element.addEventListener('mouseover', (e) => {
console.log('Mouse over', e.target);
});element.addEventListener('touchstart', (e) => {
console.log('Touch start', e.touches);
});const event = new CustomEvent('myEvent', {
detail: { message: 'Hello' }
});
element.dispatchEvent(event);// 创建 SVG 元素必须使用 createElementNS
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
const rect = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');rect.setAttribute('x', '10');
rect.setAttribute('y', '10');
rect.setAttribute('width', '50');
rect.setAttribute('height', '50');
rect.setAttribute('fill', 'blue');svg.appendChild(rect);
document.body.appendChild(svg);function screenToSVG(svg, x, y) {
const pt = svg.createSVGPoint();
pt.x = x;
pt.y = y;
return pt.matrixTransform(svg.getScreenCTM().inverse());
}function SVGToScreen(svg, x, y) {
const pt = svg.createSVGPoint();
pt.x = x;
pt.y = y;
return pt.matrixTransform(svg.getScreenCTM());
}