简体   繁体   English

FabricJS画布对象迭代

[英]Fabricjs canvas objects iterarion

I got some problems with code below : 我在下面的代码中遇到了一些问题:

var canvas = new fabric.Canvas('c');
canvas.selection = false;
fabric.loadSVGFromURL('./svg/1.svg',
    function (objects) {
        canvas.add.apply(canvas, objects);
        canvas.renderAll();
    }); -- this part is working
obj = canvas.getObjects();
obj.forEach(function (item, i) {
    console.log('plz work');
    item.setColor('red');
    item.set('selectable', false);
    canvas.renderAll();
}); - this isn't working 

When i write this code in js file it's not working, but when i run it in browser console it works perfectly. 当我在js文件中编写此代码时,它不起作用,但是当我在浏览器控制台中运行它时,它可以完美运行。 What's wrong with it? 它出什么问题了?

This is because, obj array has no objects in it (meaning it­ 's empty), when you are iterating over it, as there isn't any other objects on the canvas, and since loadSVGFromURL method is asynchronous, you can't really get hold of the SVG objects until it­ 's properly loaded and added to the canvas. 这是因为, obj阵列中有没有对象(这意味着它是空 ),当你迭代它,因为没有在画布上的任何其他对象,因为loadSVGFromURL方法是异步的,你不能真正获得SVG对象的搁置,直到它正确加载并添加到画布上。

To resolve this, simply do the iteration inside the callback function of loadSVGFromURL . 要解决此问题,只需在loadSVGFromURL的回调函数内进行loadSVGFromURL

Here is the working code : 这是工作代码:

 var canvas = new fabric.Canvas('c'); canvas.selection = false; fabric.loadSVGFromURL('https://istack.000webhostapp.com/1tf.svg', function(objects) { canvas.add.apply(canvas, objects); canvas.renderAll(); //do the iteration here obj = canvas.getObjects(); obj.forEach(function(item, i) { console.log('plz work'); item.setColor('red'); item.set('selectable', false); canvas.renderAll(); }); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.16/fabric.min.js"></script> <canvas id="c" width="200" height="200"></canvas> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM