简体   繁体   中英

How to draw a photo then a shape on top of the photo using a canvas in Ionic?

There are numerous examples out there showing how to draw things onto a canvas, however, my problem is slightly different - I want to load a photo into memory, draw a shape onto exact coordinates over the photo, THEN draw/scale the photo onto a canvas. Not sure where to start with this. Are there any relevant libraries out there I can use with ionic that will allow you to do this?

Edit 1 ~ I now have this mostly working:

private properties:

@ViewChild('mainCanvas') canvasEl: ElementRef;
private _CANVAS: any;
private _CONTEXT: any;

ionViewDidEnter():

this._CANVAS = this.canvasEl.nativeElement;
this._CONTEXT = this._CANVAS.getContext('2d');

updateCanvas():

var img = new Image();
const ctx = this._CONTEXT;
const canvas = this._CANVAS;

ctx.clearRect(0, 0, this._CANVAS.width, this._CANVAS.height);
ctx.fillStyle = "#ff0000";

img.onload = (() => {
  img.width = img.width;
  img.height = img.height;
  canvas.width = img.width;
  canvas.height = img.height;
  ctx.drawImage(img, 0, 0);
  ctx.lineWidth = 8;
  ctx.strokeStyle = "#FF0000";
  ctx.strokeRect(100, 100, 400, 400);
  ctx.scale(0.5, 0.5); // this does nothing
});

img.src = (<any>window).Ionic.WebView.convertFileSrc(path);

This draws the photo then the rectangle onto the canvas, however, the resulting image is too large to fit onto the screen, so I need to scale the canvas after all drawing is complete. I tried this with ctx.scale but the canvas remains the same size regardless of which values I specify.

You cannot draw straight onto a photo, but what you can do is create an offscreen canvas that is the same size as the photo, draw the photo to it, and then draw your shapes on top.

The result can then be drawn to your main canvas eg

// Empty image for example purposes
const img = new Image(100, 100);

// Creating a canvas for example purposes
const mainCanvas = document.createElement('canvas');
const mainCtx = mainCanvas.getContext('2d');

// Create an offscreen buffer
const bufferCanvas = document.createElement('canvas');
const bufferCtx = bufferCanvas.getContext('2d');

// Scale the buffer canvas to match our image
bufferCanvas.width = img.width;
bufferCanvas.height = img.height;

if (bufferCtx && mainCtx) {
  // Draw image to canvas
  bufferCtx.drawImage(img, 0, 0);
  // Draw a rectangle in the center
  bufferCtx.fillRect(img.width / 2 - 5, img.height / 2 - 5, 10, 10);

  // Draw the buffer to the main canvas
  mainCtx.drawImage(bufferCanvas, 0, 0);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM