如何使用Ionic中的画布在照片顶部绘制照片然后绘制形状


有很多

例子展示了如何在画布上绘制东西,但是,我的问题略有不同 - 我想将照片加载到内存中,在照片上的精确坐标上绘制形状,然后将照片绘制/缩放到画布上。不知道从哪里开始。有没有相关的库可以和离子一起使用,让你做到这一点?

编辑 1 ~ 我现在大部分工作:

私有属性:

@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);

这会将照片然后绘制矩形绘制到画布上,但是,生成的图像太大而无法容纳在屏幕上,因此我需要在所有绘图完成后缩放画布。我用ctx.scale尝试过这个,但无论我指定哪个值,画布的大小都保持不变。

您不能直接在照片上绘制,但您可以做的是创建一个与照片大小相同的屏幕外画布,将照片绘制到该画布上,然后在顶部绘制您的形状。

然后可以将结果绘制到您的主画布上,例如

// 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);
}

最新更新