Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add image to fabric canvas?

I want to add images/icons to my fabric canvas. The code given on the Fabric demo is not working.

fabric.Image.fromURL('my_image.png', function(oImg) {
canvas.add(oImg);
});

This just makes my entire canvas blank. I want to add icons as clickable elements which respond to events.

like image 826
Ankur Lathwal Avatar asked Feb 05 '16 07:02

Ankur Lathwal


People also ask

How do I add a picture to a canvas on FabricJS?

Image. fromURL('my_image. png', function(oImg) { canvas. add(oImg); });

How do you make fabric canvas?

Let's see a code example to create a Canvas using FabricJS. Since FabricJS works on top of Canvas API, we will create an HTML element using <canvas> tag and give it an id. Further, we will pass that id to the FabricJS API so that it can initialize the FabricJS Canvas instance on the <canvas> tag.

How does fabric JS work?

fabricjs Getting started with fabricjs js is a powerful and quite simple javascript library for HTML5 canvas. It provide a interactive platform to work with the HTML5 canvas. Using fabric you can create object/shapes on canvas from simple geometrical shapes to complex shapes. You can even work with images using fabric.


1 Answers

I have done a jsfiddle that loads a jpg image on the canvas, by using the fabric.Image.fromURL() function and the 'mouse:down' event. Inside the mouse:down i check if the user clicks on an object or just on the canvas.

here is a snippet of the javascript:

var canvas = new fabric.Canvas('c');
canvas.backgroundColor = 'yellow';

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: 0, top: 0 ,width:150,height:150});
 canvas.add(img1); 
});

canvas.on('mouse:down',function(event){
  if(canvas.getActiveObject()){
    alert(event.target);
  }

})

but my example also works ok ,if i dont use the extra variable:

fabric.Image.fromURL('http://fabricjs.com/assets/pug_small.jpg', function(myImg) {
 canvas.add(myImg); 
});

if you need more fabric events you can take a look here : http://fabricjs.com/events/

jsfiddle : https://jsfiddle.net/tornado1979/5nrmwtxu/

Hope helps , good luck.

like image 181
Theo Itzaris Avatar answered Oct 04 '22 10:10

Theo Itzaris