How to add image to fabric canvas?

35,581

Solution 1

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.

Solution 2

This code is working properly but you need to use fabric.js file. You also need to use fabric.js CDN file in your header.

Fabric.js CDN->

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

var imgElement = document.getElementById('my-image');
var imgInstance = new fabric.Image(imgElement, {
  left: 100,
  top: 100,
  angle: 0,
  opacity: 0.75,
  width:300,
  height:300
});
canvas.add(imgInstance);   
#my-image{display:none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.22/fabric.min.js"></script>
<canvas width="800" height="800" id="drawarea" style="border: 1px solid red;float: right">     </canvas>
<img src="https://via.placeholder.com/300.png" id="my-image" width="500px" height="500px">
Share:
35,581
Ankur Lathwal
Author by

Ankur Lathwal

Updated on July 09, 2022

Comments

  • Ankur Lathwal
    Ankur Lathwal almost 2 years

    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.