Skip to content

Commit 3455ad8

Browse files
authored
Merge pull request #65 from maxaggedon/bg-img-stretch
Background img stretch
2 parents 490cdef + 35f7174 commit 3455ad8

File tree

1 file changed

+8
-27
lines changed

1 file changed

+8
-27
lines changed

src/SketchField.jsx

Lines changed: 8 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,6 @@ class SketchField extends PureComponent {
107107
};
108108

109109
state = {
110-
parentWidth: 550,
111110
action: true
112111
};
113112
_initTools = (fabricCanvas) => {
@@ -340,9 +339,6 @@ class SketchField extends PureComponent {
340339
obj.top = tempTop;
341340
obj.setCoords()
342341
}
343-
this.setState({
344-
parentWidth: offsetWidth
345-
});
346342
canvas.renderAll();
347343
canvas.calcOffset();
348344
};
@@ -580,29 +576,15 @@ class SketchField extends PureComponent {
580576
*/
581577
setBackgroundFromDataUrl = (dataUrl, options = {}) => {
582578
let canvas = this._fc;
583-
if (options.stretched) {
584-
delete options.stretched;
585-
Object.assign(options, {
586-
width: canvas.width,
587-
height: canvas.height
588-
})
589-
}
590-
if (options.stretchedX) {
591-
delete options.stretchedX;
592-
Object.assign(options, {
593-
width: canvas.width
594-
})
595-
}
596-
if (options.stretchedY) {
597-
delete options.stretchedY;
598-
Object.assign(options, {
599-
height: canvas.height
600-
})
601-
}
602579
let img = new Image();
603580
img.setAttribute('crossOrigin', 'anonymous');
604-
img.onload = () => canvas.setBackgroundImage(new fabric.Image(img),
605-
() => canvas.renderAll(), options);
581+
const { stretched, stretchedX, stretchedY, ...fabricOptions } = options
582+
img.onload = () => {
583+
const imgObj = new fabric.Image(img);
584+
if (stretched || stretchedX) imgObj.scaleToWidth(canvas.width)
585+
if (stretched || stretchedY) imgObj.scaleToHeight(canvas.height)
586+
canvas.setBackgroundImage(imgObj, () => canvas.renderAll(), fabricOptions)
587+
};
606588
img.src = dataUrl
607589
};
608590

@@ -687,8 +669,7 @@ class SketchField extends PureComponent {
687669
componentWillUnmount = () => window.removeEventListener('resize', this._resize);
688670

689671
componentDidUpdate = (prevProps, prevState) => {
690-
if (this.state.parentWidth !== prevState.parentWidth
691-
|| this.props.width !== prevProps.width
672+
if (this.props.width !== prevProps.width
692673
|| this.props.height !== prevProps.height) {
693674

694675
this._resize()

0 commit comments

Comments
 (0)