Reputation: 1122
i try to reader SVG in Canvas using fabric js and File Reader API
the following code for Image and it will work with SVG but it will not use full functionality like change color (setFill) and other which work only for SVGs
var reader = new FileReader(), input = document.getElementById('imgFile');
reader.onload = function (event) {
//loadSVGFromString
var imgObj = new Image();
imgObj.src = event.target.result;
imgObj.onload = function () {
// start fabricJS stuff
var coord = getRandomLeftTop();
var image = new fabric.Image(imgObj);
if($scope.ImgOption != 'bg'){
image.set({
left: coord.left,
top: coord.top
});
canvas.add(image);
}else{
image.set({
scaleY: canvas.height / imgObj.height,
scaleX: canvas.width / imgObj.width
});
canvas.setBackgroundImage(image, canvas.renderAll.bind(canvas));
}
// end fabricJS stuff
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>
Upvotes: 0
Views: 1283
Reputation: 1122
i fix this issue by check type of file if it svg i use loadSVGFromString method to render object as svg path and color it
function reader(e){
var FileType='';
if(!window.FileReader && !window.File && !window.FileList && !window.Blob){
var IEversion = detectIE();
if (IEversion !== false) {
if(IEversion == 9 || IEversion == 8) {
alertify.alert("You're useing IE v"+IEversion+", /n Pleaase upgrade IE to v10 or higher in order to use the app features!"); // in html5 works and fires alert but not in IE8
}
}
return;
}
var reader = new FileReader(), input = document.getElementById('imgFile');
reader.onload = function (event) {
var coord = getRandomLeftTop();
if(FileType == 'svg'){
fabric.loadSVGFromString(event.target.result, function(objects, options) {
var loadedObject = fabric.util.groupSVGElements(objects, options);
loadedObject.set({
left: coord.left,
top: coord.top
}).setCoords();
canvas.add(loadedObject);
});
}else{
var imgObj = new Image();
imgObj.src = event.target.result;
imgObj.onload = function () {
// start fabricJS stuff
var image = new fabric.Image(imgObj);
if($scope.ImgOption != 'bg'){
image.set({
left: coord.left,
top: coord.top
});
canvas.add(image);
}else{
image.set({
scaleY: canvas.height / imgObj.height,
scaleX: canvas.width / imgObj.width
});
canvas.setBackgroundImage(image, canvas.renderAll.bind(canvas));
}
// end fabricJS stuff
}
}
}
if (!input) {
alertify.alert("Um, couldn't find the fileinput element.");
} else if (!input.files) {
alertify.alert("This browser doesn't seem to support the `files` property of file inputs.");
} else if (!input.files[0]) {
alertify.alert("Please select a file before clicking 'Load'");
} else {
file = input.files[0];
if (file.type == 'image/svg+xml') {
FileType = 'svg';
reader.readAsText(file);//readAsText(file);
}else{
FileType = 'image';
reader.readAsDataURL(file);
}
}
}
Upvotes: 2