I am trying to show certain attributes for each object on a canvas, but I am having a difficult time writing the code to do so. E.G. I want the code below to identify the difference between a shape, text, and image objects and show attributes based off the type.
Attributes to console.log:
for each object on canavas check to see if -
- Image then URL (source) and scale <= I am having a difficult time
showing the source and name of the image.
- Text then font family, font size, color, scale
- Shape then scale and color
What do I need to add/remove/change to make it work?
Here is a JS fiddle example:
https://jsbin.com/vevihikefo/1/edit?html,js,console,output
canvas.getObjects().forEach(object=>{
if(object.isType('xyz')) { // object is a shape
console.log(object.scaleX, object.fill);
} else if(object.isType('text')) { // object is a text
console.log(object.text, object.fontFamily, object.fontSize*3, object.scaleX, object.fill);
} else { // object is an image
console.log(object.name, object.scaleX, object.fill);
}
})
There are two things that need to be added / changed, to make it work ...
- change
object.isType('xyz')
to !object.isType('text') && !object.isType('image')
( as there isn't any type called 'xyz' )
- wrap the entire code for getting the objects attributes in a function and call that function on image load, to get the image object attributes properly.
fabric.Object.prototype.objectCaching = false;
var canvas = new fabric.Canvas('canvas');
canvas.add(new fabric.Text('foo', {
fontFamily: 'Roboto',
left: 100,
top: 100,
fontSize: 25
}));
canvas.add(new fabric.Text('help', {
fontFamily: 'Roboto',
left: 100,
top: 200,
fontSize: 25
}));
canvas.add(new fabric.Triangle({
fill: 'green',
left: 200,
top: 200
}));
fabric.Image.fromURL('http://fabricjs.com/assets/pug_small.jpg', function(myImg) {
//i create an extra var for to change some image properties
var img1 = myImg.set({
left: 200,
top: 0,
width: 150,
height: 150
});
canvas.add(img1);
getAttributes();
});
canvas.renderAll();
function getAttributes() {
canvas.getObjects().forEach(object => {
if (!object.isType('text') && !object.isType('image')) { // object is a shape
console.log(object.scaleX, object.fill);
} else if (object.isType('text')) { // object is a text
console.log(object.text, object.fontFamily, object.fontSize * 3, object.scaleX, object.fill);
} else if (object.isType('image')) { // object is an image
console.log(object.name, object.scaleX, object.fill);
}
});
}
<script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
<canvas id="canvas" width="800" height="600" style="border: 1px solid #d3d3d3; position: absolute;">
Your browser does not support the canvas element.
</canvas>