向FabricJS画布添加SVG时出现TypeError(is not iterable)错误
解决FabricJS加载SVG时的"t is not iterable"错误
这个错误的核心原因是FabricJS版本兼容性问题:v5及以上版本中,loadSVGFromString方法已改为返回Promise,不再支持传统的回调函数写法,你原代码的回调写法会导致参数解析错误,触发迭代器相关报错。
解决方案:改用Promise风格写法
有两种方式可以修复,推荐使用async/await让代码更清晰:
方式1:async/await写法
let svg = `<svg viewBox="-8 -8 136 136"> <path stroke="#000000" stroke-width="8" d="m0 51.82677l0 0c0 -28.623135 23.203636 -51.82677 51.82677 -51.82677l0 0c13.745312 0 26.927654 5.4603047 36.64706 15.17971c9.719406 9.719404 15.17971 22.901749 15.17971 36.64706l0 0c0 28.623135 -23.203636 51.82677 -51.82677 51.82677l0 0c-28.623135 0 -51.82677 -23.203636 -51.82677 -51.82677zm25.913385 0l0 0c0 14.311565 11.60182 25.913387 25.913385 25.913387c14.311565 0 25.913387 -11.601822 25.913387 -25.913387c0 -14.311565 -11.601822 -25.913385 -25.913387 -25.913385l0 0c-14.311565 0 -25.913385 11.60182 -25.913385 25.913385z" fill="none"></path> </svg>`; let canvas = new fabric.Canvas("canvas"); async function loadSVG() { try { // 解构Promise返回的objects和options const [objects, options] = await fabric.loadSVGFromString(svg); const svgGroup = fabric.util.groupSVGElements(objects, options); svgGroup.set({ left: canvas.width / 2 - svgGroup.width / 2, top: canvas.height / 2 - svgGroup.height / 2 }); canvas.add(svgGroup).renderAll(); } catch (error) { console.error("SVG加载失败:", error); } } loadSVG();
方式2:.then()链式调用写法
如果不适用async函数,也可以用Promise的链式调用:
let svg = `<svg viewBox="-8 -8 136 136"> <path stroke="#000000" stroke-width="8" d="m0 51.82677l0 0c0 -28.623135 23.203636 -51.82677 51.82677 -51.82677l0 0c13.745312 0 26.927654 5.4603047 36.64706 15.17971c9.719406 9.719404 15.17971 22.901749 15.17971 36.64706l0 0c0 28.623135 -23.203636 51.82677 -51.82677 51.82677l0 0c-28.623135 0 -51.82677 -23.203636 -51.82677 -51.82677zm25.913385 0l0 0c0 14.311565 11.60182 25.913387 25.913385 25.913387c14.311565 0 25.913387 -11.601822 25.913387 -25.913387c0 -14.311565 -11.601822 -25.913385 -25.913387 -25.913385l0 0c-14.311565 0 -25.913385 11.60182 -25.913385 25.913385z" fill="none"></path> </svg>`; let canvas = new fabric.Canvas("canvas"); fabric.loadSVGFromString(svg) .then(([objects, options]) => { const svgGroup = fabric.util.groupSVGElements(objects, options); svgGroup.set({ left: canvas.width / 2 - svgGroup.width / 2, top: canvas.height / 2 - svgGroup.height / 2 }); canvas.add(svgGroup).renderAll(); }) .catch(error => console.error("SVG加载失败:", error));
替代方案:降级FabricJS版本
如果一定要使用原有的回调写法,可以将FabricJS降级到v4或更早版本,但不推荐这种方式——新版本修复了大量bug,并且提供了更现代化的API设计。
内容的提问来源于stack exchange,提问作者Jordy
相关产品推荐
相关产品推荐

