我正在做一个应用程序,需要为客户端分配名称的框。
我遵循了本教程:https://devdactic.com/ionic-canvas-drawing-files/
我的.html:
<ion-content padding>
<ion-grid>
<div class="w-100">
<ion-item class="no-border" no-padding>
<ion-label position="stacked">Assinatura</ion-label>
<canvas #imageCanvas (touchstart)="startDrawing($event)" (touchmove)="moved($event)">
</canvas>
</ion-item>
</div>
</ion-row>
</ion-grid>
</ion-content>
我的.ts:
import { Component, ViewChild } from '@angular/core';
import { Content, Platform, normalizeURL } from 'ionic-angular';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
selectedColor = "#000";
@ViewChild('imageCanvas') canvas: any;
canvasElement: any;
saveX: number;
saveY: number;
@ViewChild(Content) content: Content;
constructor(private plt: Platform){
}
ionViewDidEnter () {
this.canvasElement = this.canvas.nativeElement;
}
startDrawing(ev) {
var canvasPosition = this.canvasElement.getBoundingClientRect();
this.saveX = ev.touches[0].pageX - canvasPosition.x;
this.saveY = ev.touches[0].pageY - canvasPosition.y
}
moved(ev) {
var canvasPosition = this.canvasElement.getBoundingClientRect();
let currentX = ev.touches[0].pageX - canvasPosition.x;
let currentY = ev.touches[0].pageY - canvasPosition.y;
let ctx = this.canvasElement.getContext("2d");
ctx.lineJoin = "round";
ctx.strokeStyle = this.selectedColor;
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(this.saveX, this.saveY);
ctx.lineTo(currentX, currentY);
ctx.closePath();
ctx.stroke();
this.saveX = currentX;
this.saveY = currentY;
}
}
因此,当我在浏览器上对其进行测试时,我可以看到绘图,但是该线并没有完全出现在我用鼠标单击的位置上,而是在右侧和底部出现了一些像素。当我在手机上对其进行测试时,我遇到了同样的问题。
答案 0 :(得分:0)
您要两次调用getBoundingClientRect。
这将解决您的问题:
import { Component, ViewChild, ElementRef } from '@angular/core';
import { Content, Platform, normalizeURL } from 'ionic-angular';
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
})
export class HomePage {
selectedColor = "#000";
@ViewChild('imageCanvas') canvas: ElementRef;
private ctx: CanvasRenderingContext2D;
private position: DOMRect;
saveX: number;
saveY: number;
@ViewChild(Content) content: Content;
constructor(private plt: Platform){
}
ionViewDidEnter () {
this.ctx = this.canvas.nativeElement.getContext('2d');
this.position = this.canvas.nativeElement.getBoundingClientRect();
}
startDrawing(ev) {
this.saveX = ev.touches[0].pageX - this.position.x;
this.saveY = ev.touches[0].pageY - this.position.y
}
moved(ev) {
const currentX = ev.touches[0].pageX - this.position.x;
const currentY = ev.touches[0].pageY - this.position.y;
this.ctx.lineJoin = "round";
this.ctx.strokeStyle = this.selectedColor;
this.ctx.lineWidth = 2;
this.ctx.beginPath();
this.ctx.moveTo(this.saveX, this.saveY);
this.ctx.lineTo(currentX, currentY);
this.ctx.closePath();
this.ctx.stroke();
this.saveX = currentX;
this.saveY = currentY;
}
}