imageLoader.js
2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/**
* @author NHN Ent. FE Development Team <dl_javascript@nhn.com>
* @fileoverview Image loader
*/
import Component from '../interface/component';
import { componentNames, rejectMessages } from '../consts';
import { Promise } from '../util';
const imageOption = {
padding: 0,
crossOrigin: 'Anonymous',
};
/**
* ImageLoader components
* @extends {Component}
* @class ImageLoader
* @param {Graphics} graphics - Graphics instance
* @ignore
*/
class ImageLoader extends Component {
constructor(graphics) {
super(componentNames.IMAGE_LOADER, graphics);
}
/**
* Load image from url
* @param {?string} imageName - File name
* @param {?(fabric.Image|string)} img - fabric.Image instance or URL of an image
* @returns {Promise}
*/
load(imageName, img) {
let promise;
if (!imageName && !img) {
// Back to the initial state, not error.
const canvas = this.getCanvas();
canvas.backgroundImage = null;
canvas.renderAll();
promise = new Promise((resolve) => {
this.setCanvasImage('', null);
resolve();
});
} else {
promise = this._setBackgroundImage(img).then((oImage) => {
this.setCanvasImage(imageName, oImage);
this.adjustCanvasDimension();
return oImage;
});
}
return promise;
}
/**
* Set background image
* @param {?(fabric.Image|String)} img fabric.Image instance or URL of an image to set background to
* @returns {Promise}
* @private
*/
_setBackgroundImage(img) {
if (!img) {
return Promise.reject(rejectMessages.loadImage);
}
return new Promise((resolve, reject) => {
const canvas = this.getCanvas();
canvas.setBackgroundImage(
img,
() => {
const oImage = canvas.backgroundImage;
if (oImage && oImage.getElement()) {
resolve(oImage);
} else {
reject(rejectMessages.loadingImageFailed);
}
},
imageOption
);
});
}
}
export default ImageLoader;