Saving a canvas with a background image


Hi All,

I am trying to build a guestbook application. I need to save a canvas with a background image. But after saving the canvas the background image is not seen.

This is what I need.


This is what I get after saving the canvas. The background image is taken with the camera and it is not saved.

My code is as follows:


<canvas #myCanvas (touchstart)="touch($event)" (touchmove)="drawed($event)"></canvas>

<button ion-button icon-only (click)="saveCanvas()"><ion-icon name="bookmark"></ion-icon></button>


export class CanvasPage {
 @ViewChild('myCanvas') canvas: any;
 @Input('background-image') backgroundImage: string;

 canvasElement: any;

 constructor(public navCtrl: NavController, public navParams: NavParams, public file: File,
    public renderer: Renderer, public platform: Platform,  private base64ToGallery: Base64ToGallery) {
      this.base_image = navParams.get('image');
      this.taken_image = this.base_image.split(',')[1];

     this.canvasElement = this.canvas.nativeElement;
     this.renderer.setElementAttribute(this.canvasElement, 'width', this.platform.width() + '');
     this.renderer.setElementAttribute(this.canvasElement, 'height', this.platform.height() + '');

     // to set the image as background

     this.renderer.setElementStyle(this.canvasElement, 'backgroundImage', 'url(' + this.taken_image + ')');

     // end

   var dataUrl = this.canvasElement.toDataURL();
   let ctx = this.canvasElement.getContext('2d');   
   var data = dataUrl.split(',')[1];

   // to save the canvas as png image and navigate to the next page to show the saved image

     res =>
       this.navCtrl.push('ImagePage' , {
         source: res
       }) ,
     err => console.log('Error saving image to gallery ', err)

  // end

Anyone knows how to solve this issue? Any suggestion is appreciable.


Hey man, im trying to do something similar. However, Im not able to save the canvas drawing in the first place. Would you mind helping me out with that?


So to save the canvas with the image in it you have to ‘draw’ the image into the canvas and not just set it as “background”.

You need to use this method below. Then allow users to draw on top of it and then save it.

Basically instead of this:

// to set the image as background
this.renderer.setElementStyle(this.canvasElement, ‘backgroundImage’, ‘url(’ + this.taken_image + ‘)’);

do this:

// draw image into canvas:

this.ctx = this.canvasElement.getContext(‘2d’);
this.ctx.drawImage(this.taken_image, width, height);