SVG Import
About 3 min
SVG Import
Import SVG vector graphics into WebCAD and convert them into CAD entities.
Overview
| Method | Description |
|---|---|
IMPORTSVG command | Opens a dialog with visual import configuration options |
parseSvgToWebcad() API | Programmatically parses SVG content |
Command Mode
IMPORTSVG Command
await Engine.editor.executerWithOp('IMPORTSVG');The command opens an import dialog with the following capabilities:
Input method
- Select a local SVG file
- Paste SVG content directly
Display settings
- Show lineweight
- Enable fill
- Lineweight scale ratio
Color processing
- White color handling
- Black color handling
Insert options
- Allow scaling
- Allow rotation
Real-time preview
- Original SVG appearance
- WebCAD converted result
API Mode
Complete Workflow
const {
Engine, Point2D,
getWebCadCoreService, CadDocument, regen
} = vjcad;
// 1. SVG content
const svgContent = `
<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200" viewBox="0 0 200 200">
<rect x="20" y="20" width="60" height="40" fill="none" stroke="#ff0000" stroke-width="2"/>
<circle cx="150" cy="50" r="30" fill="none" stroke="#00ff00" stroke-width="2"/>
<line x1="20" y1="100" x2="180" y2="100" stroke="#0000ff" stroke-width="2"/>
</svg>
`;
// 2. Initialize WASM service
const wasmService = getWebCadCoreService();
await wasmService.initWasm();
// 3. Parse SVG into WebCAD data
const webcadData = await wasmService.parseSvgToWebcad(
svgContent,
0, // whiteColorProcessing
0, // blackColorProcessing
0, // enableFill
1, // displayLineWeight
1.0 // lineWeightScale
);
if (!webcadData) {
throw new Error("SVG parse failed");
}
// 4. Parse WebCAD data
const parsedData = JSON.parse(webcadData);
const entities = parsedData.entities || [];
// 5. Calculate bounds and base point
let basePoint = [0, 0];
if (parsedData.bounds && parsedData.bounds.length === 4) {
const [minX, minY, maxX, maxY] = parsedData.bounds;
basePoint = [(minX + maxX) / 2, (minY + maxY) / 2];
}
// 6. Build temporary document data
const docData = {
appName: "WebCAD SVG Import",
docVer: 0.3,
dbBlocks: {
"*Model": {
blockId: "*Model",
name: "*Model",
isLayout: false,
basePoint: [0, 0],
lookPt: [0, 0],
twistAngle: 0,
zoom: 1,
UCSXANG: 0,
UCSORG: [0, 0],
items: entities
}
},
dbLayers: [{
name: "0",
layerId: "0",
layerOn: true,
color: 7,
lineType: "Continuous",
lineWeight: -3,
plottable: true
}],
dbTextStyles: [],
dbLayouts: [{
layoutId: 0,
name: "Model",
spaceName: "*Model"
}]
};
// 7. Create temporary document
const symbolDoc = new CadDocument();
await symbolDoc.fromDb(docData);
// 8. Merge entities into current document
const insertPoint = new Point2D(0, 0);
const basePt = new Point2D(basePoint[0], basePoint[1]);
const modelBlock = symbolDoc.blocks.itemByName("*Model");
for (const entity of modelBlock.items) {
if (!entity.isAlive) continue;
const cloned = entity.clone();
cloned.move(basePt, insertPoint);
Engine.addEntities(cloned);
}
// 9. Refresh view
regen();
Engine.zoomExtents();parseSvgToWebcad Parameters
wasmService.parseSvgToWebcad(
svgContent, // SVG content string
whiteColorProcessing, // White color handling mode
blackColorProcessing, // Black color handling mode
enableFill, // Whether to enable fill
displayLineWeight, // Whether to display lineweight
lineWeightScale // Lineweight scale ratio
);Color Handling Modes
| Value | Description |
|---|---|
| 0 | Keep as-is |
| 1 | Auto invert (white to black, black to white) |
| 2 | Filter out (do not import that color) |
Fill and Lineweight
| Parameter | Value | Description |
|---|---|---|
enableFill | 0 | Disable fill |
enableFill | 1 | Enable fill |
displayLineWeight | 0 | Do not display lineweight |
displayLineWeight | 1 | Display lineweight |
lineWeightScale | 1.0 | 1:1 lineweight |
lineWeightScale | 2.0 | Lineweight enlarged 2x |
Supported SVG Elements
| Element | Converted To |
|---|---|
<line> | LineEnt |
<rect> | PolylineEnt |
<circle> | CircleEnt |
<ellipse> | EllipseEnt |
<polyline> | PolylineEnt |
<polygon> | PolylineEnt (closed) |
<path> | PolylineEnt / SplineEnt |
<text> | TextEnt |
Return Data Format
parseSvgToWebcad() returns a JSON string which, after parsing, contains:
{
entities: [...], // Entity array
bounds: [minX, minY, maxX, maxY] // Bounding range
}Simplified Wrapper Example
const { Engine, Point2D, getWebCadCoreService, CadDocument, regen } = vjcad;
/**
* Import SVG content into the current document
* @param svgContent SVG content string
* @param insertPoint insertion point (optional, defaults to origin)
* @param options import options
*/
async function importSvg(svgContent, insertPoint = new Point2D(0, 0), options = {}) {
const {
whiteColorProcessing = 0,
blackColorProcessing = 0,
enableFill = 0,
displayLineWeight = 1,
lineWeightScale = 1.0
} = options;
// Initialize WASM
const wasmService = getWebCadCoreService();
await wasmService.initWasm();
// Parse SVG
const webcadData = await wasmService.parseSvgToWebcad(
svgContent,
whiteColorProcessing,
blackColorProcessing,
enableFill,
displayLineWeight,
lineWeightScale
);
if (!webcadData) {
throw new Error("SVG parse failed");
}
const parsedData = JSON.parse(webcadData);
const entities = parsedData.entities || [];
if (entities.length === 0) {
throw new Error("No entities were parsed");
}
// Calculate base point
let basePoint = [0, 0];
if (parsedData.bounds?.length === 4) {
const [minX, minY, maxX, maxY] = parsedData.bounds;
basePoint = [(minX + maxX) / 2, (minY + maxY) / 2];
}
// Build temporary document
const docData = {
appName: "WebCAD SVG Import",
docVer: 0.3,
dbBlocks: {
"*Model": {
blockId: "*Model",
name: "*Model",
isLayout: false,
basePoint: [0, 0],
lookPt: [0, 0],
twistAngle: 0,
zoom: 1,
UCSXANG: 0,
UCSORG: [0, 0],
items: entities
}
},
dbLayers: [{
name: "0", layerId: "0", layerOn: true,
color: 7, lineType: "Continuous", lineWeight: -3, plottable: true
}],
dbTextStyles: [],
dbLayouts: [{ layoutId: 0, name: "Model", spaceName: "*Model" }]
};
const symbolDoc = new CadDocument();
await symbolDoc.fromDb(docData);
// Merge entities
const modelBlock = symbolDoc.blocks.itemByName("*Model");
const basePt = new Point2D(basePoint[0], basePoint[1]);
const addedEntities = [];
for (const entity of modelBlock.items) {
if (!entity.isAlive) continue;
const cloned = entity.clone();
cloned.move(basePt, insertPoint);
Engine.addEntities(cloned);
addedEntities.push(cloned);
}
regen();
return addedEntities;
}
// Usage example
const svgContent = `<svg>...</svg>`;
const entities = await importSvg(svgContent, new Point2D(100, 100), {
enableFill: 1,
lineWeightScale: 2.0
});
console.log(`Imported ${entities.length} entities`);Import from File
// Create file input
const input = document.createElement('input');
input.type = 'file';
input.accept = '.svg';
input.onchange = async (e) => {
const file = e.target.files[0];
if (!file) return;
// Read file content
const reader = new FileReader();
reader.onload = async (event) => {
const svgContent = event.target.result;
// Import SVG
const entities = await importSvg(svgContent);
console.log(`Imported ${entities.length} entities from ${file.name}`);
Engine.zoomExtents();
};
reader.readAsText(file);
};
// Trigger file selection
input.click();Notes
- WASM initialization: the first call requires initializing the WASM service
- Color mapping: SVG colors are automatically mapped to CAD color indices
- Complex paths: complex
<path>elements may be converted to polylines or splines - Text handling: SVG text requires corresponding font support
- Gradients/filters: advanced SVG effects such as gradients and filters are not supported