2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 export interface ICanvasImage {
30 export class ImageCreatorService {
31 static '$inject' = ['$q'];
32 private _canvas: HTMLCanvasElement;
34 constructor(private $q: ng.IQService) {
35 this._canvas = <HTMLCanvasElement>$('<canvas>')[0];
36 this._canvas.setAttribute('style', 'display:none');
38 let body = document.getElementsByTagName('body')[0];
39 body.appendChild(this._canvas);
43 * Create an image composed of different image layers
49 getMultiLayerBase64Image(canvasImages: ICanvasImage[], canvasWidth?: number, canvasHeight?: number): ng.IPromise<string> {
50 const deferred = this.$q.defer<string>();
52 if (canvasImages && canvasImages.length === 0) {
56 //If only width was set, use it for height, otherwise use first canvasImage height
57 canvasHeight = canvasHeight || canvasImages[0].height;
58 canvasWidth = canvasWidth || canvasImages[0].width;
62 const onImageLoaded = () => {
64 if (imagesLoaded < canvasImages.length) {
67 this._canvas.setAttribute('width', canvasWidth.toString());
68 this._canvas.setAttribute('height', canvasHeight.toString());
69 const canvasCtx = this._canvas.getContext('2d');
70 canvasCtx.clearRect(0, 0, this._canvas.width, this._canvas.height);
71 images.forEach((image, index) => {
72 const canvasImage = canvasImages[index];
73 canvasCtx.drawImage(image, canvasImage.x, canvasImage.y, canvasImage.width, canvasImage.height);
75 let base64Image = this._canvas.toDataURL();
76 deferred.resolve(base64Image);
78 canvasImages.forEach(canvasImage => {
79 let image = new Image();
80 image.onload = onImageLoaded;
81 image.src = canvasImage.src;
84 return deferred.promise;