capacitor-community / barcode-scanner

A fast and efficient (QR) barcode scanner for Capacitor
MIT License
437 stars 167 forks source link

How cancel scan QR? #304

Open javico-dev11 opened 2 months ago

javico-dev11 commented 2 months ago

Good morning, is there any way that when you start scanning the QR code, you can cancel the scan, a button or something?

umeshsarkar commented 1 month ago

yes, you can cancel the scan on the scan screen. here I can recommend one solution.

qrcode.page.html

<ion-content class="scanner-background">
  <div class="button-container">
    <button (click)="startScan()" [disabled]="isScanning">Start Scan</button>
    <button class="stop-scan-button" (click)="stopScan()" [disabled]="!isScanning">Stop Scan</button>
    <p>{{ scanResult }}</p>
  </div>
  <div class="scanner-container" *ngIf="isScanning">
    <div id="scanner-area" class="scanner-overlay"></div>
  </div>
</ion-content>

qrcode.page.ts

export class QrCode {
  scanResult: string | undefined;
  isScanning = false;

  constructor() {}

  async startScan(): Promise<void> {
    this.isScanning = true;
    await BarcodeScanner.checkPermission({ force: true });
    BarcodeScanner.hideBackground(); // make background of WebView transparent
    this.scan();
  }

  async scan() {
    const result = await BarcodeScanner.startScan({ targetedFormats: [SupportedFormat.QR_CODE] });
    if (result.hasContent) {
      this.scanResult = result.content;
      this.scan();
    } else if (this.isScanning) {
      this.scan();
    }
  }

  async stopScan(): Promise<void> {
    this.isScanning = false;
    await BarcodeScanner.stopScan();
    BarcodeScanner.showBackground(); // restore background
  }
}

qrcode.page.scss

.button-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-top: 20px;

  button {
    margin: 10px;
  }

  p {
    margin-top: 20px;
  }
}

.scanner-container {
  position: relative;
  height: 100vh;
}

.scanner-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 5;
}

.stop-scan-button {
  position: fixed;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 10;
  padding: 10px 20px;
  background-color: red;
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 16px;
}