-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathHomePage.vue
457 lines (386 loc) · 11.4 KB
/
HomePage.vue
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
<script setup lang="ts">
import {onMounted, ref, watch} from "vue";
import {IonContent, IonHeader, IonPage, IonTitle, IonToolbar, IonButton, IonIcon, IonRange, IonToggle} from '@ionic/vue';
import {CameraPreview, CameraPreviewOptions} from '@capacitor-community/camera-preview';
import {addCircleOutline, camera, close, refresh, removeCircleOutline} from 'ionicons/icons';
import {Capacitor} from "@capacitor/core";
// Internal variables
const IMAGE_QUALITY = 85;
const photoSelector = '#photo .image';
const ZOOM_STEPS = 10;
const MIN_ZOOM = 1;
const MAX_ZOOM_LIMIT = 5;
// Refs
const previewStarted = ref(false)
const canTakePhoto = ref(true)
const cameraText = ref('')
const cameraTextClass = ref('')
const imgSrc = ref('')
const imageLoadingHeight = ref(0);
const maxZoom = ref(0)
const currentZoom = ref(0)
const zoomRangeRef = ref()
const zoomStep = ref();
const storeToFile = ref(false);
const setNoCameraAvailable = (reason: string) => {
canTakePhoto.value = false;
cameraText.value = reason
cameraTextClass.value = 'danger'
}
const unsetNoCameraAvailable = () => {
canTakePhoto.value = true;
cameraText.value = ''
cameraTextClass.value = ''
}
const onPressFlip = async () => {
try {
await CameraPreview.flip();
} catch (e: any) {
const errorMessage = e.message;
console.error(`Error flipping camera: ${errorMessage}`);
}
}
const onTakePhoto = async (newSrc: string) => {
imgSrc.value = newSrc;
}
const onPressTakePhoto = async () => {
try {
const result = await CameraPreview.capture({
quality: IMAGE_QUALITY
});
let imgSrc;
if(storeToFile.value){
imgSrc = Capacitor.convertFileSrc(result.value);
}else{
imgSrc = 'data:image/jpeg;base64,' + result.value;
}
await onTakePhoto(imgSrc)
await stopCameraPreview();
} catch (e: any) {
const errorMessage = e.message;
setNoCameraAvailable(errorMessage);
}
}
const startCameraPreview = () => {
requestAnimationFrame(() => {
_startCameraPreview();
})
}
const _startCameraPreview = async () => {
if (previewStarted.value) {
return;
}
if (!canTakePhoto.value) {
console.warn('Camera preview not available');
return;
}
// Get the viewport offset and dimensions of the camera preview
const cameraPreview = document.getElementById('camera-preview');
const cameraPreviewRect = cameraPreview?.getBoundingClientRect();
const cameraPreviewOptions: CameraPreviewOptions = {
parent: 'camera-preview',
x: Math.ceil(cameraPreviewRect?.x || 0),
y: Math.ceil(cameraPreviewRect?.y || 0) + 1,
width: Math.ceil(cameraPreviewRect?.width || 0) - 2,
height: Math.ceil(cameraPreviewRect?.height || 0) - 2,
position: 'rear',
enableZoom: true,
toBack: false,
storeToFile: storeToFile.value,
lockAndroidOrientation: true,
disableExifHeaderStripping: false,
maxZoomLimit: MAX_ZOOM_LIMIT,
}
try {
unsetNoCameraAvailable();
// make sure it's stopped before starting
try{await CameraPreview.stop();} catch(e){
null; // ignore
}
await CameraPreview.start(cameraPreviewOptions);
try{
const _maxZoom = await CameraPreview.getMaxZoom(),
deviceMaxZoom = _maxZoom.value;
console.log('Device max zoom:', deviceMaxZoom)
maxZoom.value = Math.min(deviceMaxZoom, MAX_ZOOM_LIMIT);
zoomStep.value = maxZoom.value / ZOOM_STEPS;
const _currentZoom = await CameraPreview.getZoom();
currentZoom.value = _currentZoom.value;
}catch (e: any) {
console.error(`Error getting camera zoom: ${e.message}`);
}
document.documentElement.classList.add('camera-preview');
previewStarted.value = true;
} catch (e: any) {
const errorMessage = e.message;
if (errorMessage.match("camera already started")) {
// Try again
console.debug(`Camera already started. Trying again...`)
await stopCameraPreview();
await _startCameraPreview();
} else {
setNoCameraAvailable(errorMessage);
}
}
}
const stopCameraPreview = async () => {
try {
await CameraPreview.stop();
document.documentElement.classList.remove('camera-preview');
previewStarted.value = false;
} catch (e) {
const errorMessage = e as string;
setNoCameraAvailable(errorMessage);
console.error(`Error stopping camera preview: ${errorMessage}`);
}
}
const resolvePhotoAspectRatio = () => {
const photo = document.querySelector(photoSelector) as HTMLImageElement;
const width = photo.offsetWidth;
const height = photo.offsetHeight;
const aspectRatio = width / height;
// get the parent element of the photo
const parent = photo.parentElement as HTMLElement;
// reset
parent.classList.remove('landscape')
parent.classList.remove('portrait');
parent.style.maxHeight = 'none';
if (aspectRatio > 1) {
parent.classList.add('landscape');
} else {
parent.classList.add('portrait');
parent.style.maxHeight = width + 'px';
}
}
const waitForPhotoToRender = () => {
const photo = document.querySelector(photoSelector) as HTMLElement;
if (photo) {
const height = (photo as HTMLElement).offsetHeight;
if (height > 0) {
// if height is same as last time, image has finished rendering
if (height === imageLoadingHeight.value) {
resolvePhotoAspectRatio();
return;
} else {
imageLoadingHeight.value = height;
}
}
}
requestAnimationFrame(waitForPhotoToRender);
}
const onChangeZoom = (zoom:number) => {
try {
CameraPreview.setZoom({zoom});
}catch (e: any) {
console.error(`Error setting camera zoom: ${e.message}`);
}
}
const onTapZoomOut = () => {
let zoom = Math.max(MIN_ZOOM, currentZoom.value - zoomStep.value);
zoom = Math.round(zoom);
currentZoom.value = zoom;
}
const onTapZoomIn = () => {
let zoom = Math.min(maxZoom.value, currentZoom.value + zoomStep.value);
zoom = Math.round(zoom);
currentZoom.value = zoom;
}
watch(imgSrc, (value: string) => {
if (value) {
imageLoadingHeight.value = 0;
waitForPhotoToRender();
}
})
watch(currentZoom, (value: number, oldValue:number) => {
if(value === oldValue) return;
console.log('Zoom changed to', value);
onChangeZoom(value);
})
watch(maxZoom, (value: number) => {
console.log('Max zoom changed to', value);
})
watch (zoomStep, (value: number) => {
console.log('Zoom step changed to', value);
})
const onRejectPhoto = async () => {
imgSrc.value = '';
startCameraPreview();
}
const onZoomLevelChanged = (event: any) => {
const zoom = event.level;
if(zoom != undefined){
debouncedZoomLevelChange(zoom);
}
}
const debounce = (func: (...args: any[]) => void, wait: number) => {
let timeout: any;
return function(this: any, ...args: any[]) {
clearTimeout(timeout);
// eslint-disable-next-line prefer-spread
timeout = setTimeout(() => func.apply(null, args), wait);
}
}
const zoomLevelChanged = (zoom: number) => {
console.log(`zoom changed to: ${zoom}`);
currentZoom.value = zoom;
}
const debouncedZoomLevelChange = debounce(zoomLevelChanged, 100);
const onChangeStoreToFile = (value: boolean) => {
storeToFile.value = value;
imgSrc.value = '';
}
onMounted(async () => {
(window as any).addEventListener('CameraPreview.zoomLevelChanged', onZoomLevelChanged);
startCameraPreview();
try{
const cameraCharacteristics = await CameraPreview.getCameraCharacteristics();
console.dir(cameraCharacteristics);
}catch (e: any) {
console.error(`Error getting camera characteristics: ${e.message}`);
}
})
</script>
<template>
<ion-page>
<ion-header :translucent="true">
<ion-toolbar>
<ion-title>Capacitor Camera Preview Test</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-header collapse="condense">
<ion-toolbar>
<ion-title size="large">Capacitor Camera Preview Test</ion-title>
</ion-toolbar>
</ion-header>
<div class="content-inner">
<div id="camera" v-if="!imgSrc">
<div id="camera-preview" class="image"></div>
<p class="text" v-if="cameraText" v-html="cameraText" :class="cameraTextClass"></p>
<div class="buttons">
<ion-button :disabled="!canTakePhoto" @click="onPressTakePhoto()">
<ion-icon slot="end" :icon="camera" size="large"/>
<span>Take photo</span>
</ion-button>
<ion-button :disabled="!canTakePhoto" @click="onPressFlip()">
<ion-icon slot="end" :icon="refresh" size="large"/>
<span>Flip camera</span>
</ion-button>
</div>
<ion-range
v-model="currentZoom"
ref="zoomRangeRef"
aria-label="Camera zoom level"
:max="maxZoom"
:min="MIN_ZOOM"
>
<ion-icon @click="onTapZoomOut()" slot="start" :icon="removeCircleOutline" color="primary"></ion-icon>
<ion-icon @click="onTapZoomIn()" slot="end" :icon="addCircleOutline" color="primary"></ion-icon>
</ion-range>
<div class="store-to-file">
<ion-toggle
:enable-on-off-labels="true"
@ionChange="onChangeStoreToFile($event.target.checked)"
:checked="storeToFile">
Store to file
</ion-toggle>
</div>
</div>
<div class="photo-layout" v-else>
<div id="photo">
<div class="image-container">
<img :src="imgSrc" class="image"/>
</div>
<div class="photo buttons">
<ion-button @click="onRejectPhoto()" color="danger">
<ion-icon slot="icon-only" :icon="close"/>
</ion-button>
</div>
</div>
</div>
</div>
</ion-content>
</ion-page>
</template>
<style scoped lang="scss">
.buttons {
text-align: center;
}
ion-content {
--background: transparent;
&, #content {
overflow: hidden;
}
}
ion-title {
color: white !important;
}
.content-inner {
--clamped-p-font-size: 1rem;
--preview-padding: var(--clamped-p-font-size);
--min-preview-size: calc(100vw - 2 * var(--preview-padding));
--max-preview-size: 40vh;
--preview-size: min(var(--min-preview-size), var(--max-preview-size));
height: 100%;
display: flex;
flex-direction: column;
justify-content: space-between;
#camera {
#camera-preview.image {
height: var(--preview-size);
width: var(--preview-size);
margin-left: auto;
margin-right: auto;
z-index: 1;
text-align: center;
}
p {
background: rgba(255, 255, 255, 0.75);
padding: var(--clamped-p-font-size);
}
.text {
text-align: center;
}
.text {
&.danger {
color: var(--ion-color-danger);
}
}
ion-range{
padding: 20px;
}
.store-to-file{
width: 100%;
display: flex;
justify-content: center;
}
}
#photo{
margin-bottom: var(--clamped-p-font-size);
padding: 0 var(--clamped-p-font-size) var(--clamped-p-font-size) var(--clamped-p-font-size);
.image{
width: var(--preview-size);
margin-left: auto;
margin-right: auto;
}
.text{
text-align: center;
}
}
.buttons {
display: flex;
flex-direction: column;
justify-content: space-around;
align-items: center;
margin-top: var(--clamped-p-font-size);
}
.image-container {
height: auto;
object-fit: cover;
object-position: center center;
overflow: hidden;
display: flex;
align-items: center;
}
}
</style>