我正在尝试使用input元素来加载图像,并希望将其设置为画布的背景图像。我正在使用Fabric JS。
以下是我的尝试
$(function(){
var canvas = new fabric.Canvas('canvas');
$('#importimage').on('change', function(e){
//method 1
imageUrl = $(this).val();
imageUrl = petUtil.getImage(imageUrl);
_canvas = canvas;
fabric.Image.fromURL(imageUrl , function(image)
{
image.set({ left:left , top:top , angle:angle , cornersize:10 });
top_shiv = $('.upper-canvas').attr('height');
left_shiv = $('.upper-canvas').attr('width');
top= top_shiv/5;
left= _canvasWidth/4;
image.set({left:left , top:top ,
width:window.newwidth,height:window.newheight });
image.scale(scale).setCoords();
_canvas.add(image);
_canvas.setWidth(window.newwidth);
_canvas.setHeight(window.newheight);
_canvas.renderAll();
}, { crossOrigin: 'Anonymous' });
//method 2
var file = e.target.files[0];
alert(file);
var reader = new FileReader();
reader.onload = function(f) {
var data = f.target.result;
fabric.Image.fromURL(data, function(img) {
canvas.setHeight(100);
canvas.setWidth(100);
canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas));
});
};
});
});
这两种方法都不起作用jsfiddle https://jsfiddle.net/upatg6ge/12/
答案 0 :(得分:0)
只需在reader.onload回调下面添加一行,如下所示:
var file = e.target.files[0];
alert(file);
var reader = new FileReader();
reader.onload = function(f) {
var data = f.target.result;
fabric.Image.fromURL(data, function(img) {
canvas.setHeight(100);
canvas.setWidth(100);
canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas));
});
};
// newly added line :
reader.readAsDataURL(file);