Javascript 如何将图像添加到织物画布?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35218368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:25:14  来源:igfitidea点击:

How to add image to fabric canvas?

javascripthtmlcanvasfabricjs

提问by Ankur Lathwal

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

我想在我的织物画布上添加图像/图标。Fabric 演示中给出的代码不起作用。

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.

这只会让我的整个画布空白。我想添加图标作为响应事件的可点击元素。

回答by Theo Itzaris

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:downi check if the user clicks on an object or just on the canvas.

我已经完成了一个 jsfiddle,通过使用fabric.Image.fromURL()函数和“ mouse:down”事件在画布上加载了一个 jpg 图像 。在鼠标内部:向下我检查用户是否点击了一个对象或只是在画布上。

here is a snippet of the javascript:

这是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/

如果您需要更多结构事件,您可以在这里查看:http: //fabricjs.com/events/

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

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

Hope helps , good luck.

希望有帮助,祝你好运。

回答by manoj chauhan

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 文件。您还需要在标头中使用 fabric.js CDN 文件。

Fabric.js CDN->

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">