diff --git a/src/SketchField.jsx b/src/SketchField.jsx index 89741efd..7bd8fc10 100644 --- a/src/SketchField.jsx +++ b/src/SketchField.jsx @@ -520,6 +520,18 @@ class SketchField extends PureComponent { * @param options */ setBackgroundFromDataUrl = (dataUrl, options = {}) => { + let img = new Image(); + img.onload = () => this.setBackgroundFromImage(img); + img.src = dataUrl + }; + + /** + * Sets the background from an Image object + * + * @param image the Image object to be used as a background + * @param options + */ + setBackgroundFromImage = (image, options = {}) => { let canvas = this._fc; if (options.stretched) { delete options.stretched; @@ -540,10 +552,37 @@ class SketchField extends PureComponent { height: canvas.height }) } - let img = new Image(); - img.onload = () => canvas.setBackgroundImage(new fabric.Image(img), - () => canvas.renderAll(), options); - img.src = dataUrl + canvas.setBackgroundImage(new fabric.Image(image), () => canvas.renderAll(), options); + }; + + /** + * Sets the background from the url given + * + * @param url the url of the image to be used as a background + * @param options + */ + setBackgroundFromUrl = (url, options = {}) => { + let canvas = this._fc; + if (options.stretched) { + delete options.stretched; + Object.assign(options, { + width: canvas.width, + height: canvas.height + }) + } + if (options.stretchedX) { + delete options.stretchedX; + Object.assign(options, { + width: canvas.width + }) + } + if (options.stretchedY) { + delete options.stretchedY; + Object.assign(options, { + height: canvas.height + }) + } + canvas.setBackgroundImage(url, () => canvas.renderAll(), options); }; addText = (text, options = {}) => { diff --git a/types/index.d.ts b/types/index.d.ts index da0a503c..d8cb0176 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -1,6 +1,13 @@ declare module 'react-sketch' { import * as React from 'react' + export interface BackgroundImageOptions { + stretched?: boolean + stretchedX?: boolean + stretchedY?: boolean + [name: string]: any + } + export class SketchField extends React.PureComponent<{ // the color of the line lineColor?: string @@ -169,12 +176,23 @@ declare module 'react-sketch' { * @param dataUrl the dataUrl to be used as a background * @param options */ - setBackgroundFromDataUrl(dataUrl: string, options?: { - stretched?: boolean - stretchedX?: boolean - stretchedY?: boolean - [name: string]: any - }): void + setBackgroundFromDataUrl(dataUrl: string, options?: BackgroundImageOptions): void + + /** + * Sets the background from an Image object + * + * @param image the Image object to be used as a background + * @param options + */ + setBackgroundFromImage(image: HTMLImageElement, options?: BackgroundImageOptions): void + + /** + * Sets the background from the url given + * + * @param url the url of the image to be used as a background + * @param options + */ + setBackgroundFromUrl(url: string, options?: BackgroundImageOptions): void addText(text: string, options?: {}): void