How to select child elements after using groupSVGElements

倖福魔咒の 提交于 2019-12-06 03:33:48

You can use canvas.add.apply instead groupSVGElements, so you can : have each element to manipulate

var shapesSvg = '<?xml version="1.0" encoding="UTF-8" standalone="no"?><svg version="1.1" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" width="320" height="240" viewBox="0 0 320 240"><rect id="rect" x="5" y="50" width="100" height="100" style="fill: rgb(255,0,0);"></rect> <circle id="circle" cx="165" cy="100" r="50" style="fill: rgb(0,255,0);"/></svg>';

var canvas = new fabric.Canvas('canvas');

canvas.setHeight($(window).height());
canvas.setWidth($(window).width());


fabric.loadSVGFromString(shapesSvg, function(objects, options) {
  canvas.add.apply(canvas, objects);
  canvas.renderAll();
});
html,
body {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>
<canvas id="canvas"></canvas>

Description

The following code detects any object on the screen by it's color, not the best thought.

Code

var $canvas = {
    activePaths: []
};

// Bind to `onMouseDown` event.
function onMouseDown = function (options) {

    var mousePos = canvas.getPointer(options.e);
    mousePos.x = parseInt(mousePos.x);
    mousePos.y = parseInt(mousePos.y);

    var width =  canvas.getWidth();
    var height = canvas.getHeight();

    var pixels = canvas.getContext().getImageData(0, 0, width, height);
    var pixel = (mousePos.x + mousePos.y * pixels.width) * 4;

    var activePathsColor = new fabric['Color']('rgb(' + pixels.data[pixel] + ',' + pixels.data[pixel + 1] + ',' + pixels.data[pixel + 2] + ')');
    var colorHex = '#' + activePathsColor.toHex().toLowerCase();

    var activeObject = canvas.getActiveObject();
    var activePath = [];

    // Check if active objects are type of `group`, if so push the selected path.
    if(activeObject.type == 'group') {

          for (var i = 0; i < activeObject.getObjects().length; i++) {
            var path = activeObject.getObjects()[i];
            if (path.getFill().toLowerCase() == colorHex) {
                $canvas.activePaths.push(path);
            }
        }

    }

}

References

Events: http://fabricjs.com/events/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!