问题
Using angular In a foreach loop i am generating a canvas using Fabricjs and attaching images and text. What i need to know is how to keep track of the multiple canvas variables being set.
angular.forEach($scope.data, function (obj, key) {
   var newCanvas = document.createElement('canvas');
   newCanvas.id = 'variableCanvas'+key;
   var body = document.getElementById("canvasContainer");
   body.appendChild(newCanvas);
   var canvas = new fabric.Canvas('variableCanvas'+key, {
                    backgroundColor: 'rgb(215,215,215)',
                    selectionColor: 'blue',
                    width: $scope.width,
                    height: $scope.height,
                    centeredRotation: true,
                    centeredScaling: true,
                    canvasKey: key
                });
});
The problem is i need to make var canvas to be something like var canvas+key so that i can access the specific canvas variable later on to add text or other elements. Any ideas on this. When i try to name the variable var canvas+key or var canvas[key] or var canvas.key it wont work i get a error for syntax.
so later on i can do
 canvas+key.add(inputText);
because i can keep track of the key in the application
回答1:
You can define a canvas array on $scope outside your foreach loop. And then assign each canvas to $scope.canvas[key]. So your code will be like this:
$scope.canvas = [];
angular.forEach($scope.data, function (obj, key) {
   var newCanvas = document.createElement('canvas');
   newCanvas.id = 'variableCanvas'+key;
   var body = document.getElementById("canvasContainer");
   body.appendChild(newCanvas);
   $scope.canvas[key] = new fabric.Canvas('variableCanvas'+key, {
                    backgroundColor: 'rgb(215,215,215)',
                    selectionColor: 'blue',
                    width: $scope.width,
                    height: $scope.height,
                    centeredRotation: true,
                    centeredScaling: true,
                    canvasKey: key
                });
});
This way you can assess the all your canvasses as scope variable using the key.
来源:https://stackoverflow.com/questions/28355816/fabricjs-multiple-canvases-handling