javascript - 由于我的组件,无法将属性“srcObject”设置为 null
问题描述
我正在使用 Vue.Js 做一个小项目我有一个小问题srcObject
不起作用,因为我将我的代码注入到我的模态组件中,如您所见。(但如果我删除它,它会起作用<modal></modal>
错误恰好在:videoPlayer.srcObject = stream;
这是我在控制台中收到的错误消息:
Uncaught (in promise) TypeError: Cannot set property 'srcObject' of null
这是我的代码:
<template>
<div class="float-right">
<button
class="btn btn-sm btn-success"
@click="showModal = true"
data-toggle="modal"
data-target="#addContact"
>
<i class="fas fa-plus"></i> Scan
</button>
<modal size="modal-sm" title="Scan a Business Card" v-if="showModal" @close="showModal = false">
<div>
<div id="stream">
<div>
<video ref="video" id="video" width="1024" height="576" autoplay></video>
</div>
<div>
<button
class="btn btn-dark btn-lg"
style="margin-top: 5px; margin-bottom: 7px"
id="snap"
v-on:click="capture()"
>Capture</button>
</div>
<canvas ref="canvas" id="canvas" width="640" height="480"></canvas>
<ul>
<li v-for="c in captures" :key="c.id">
<img v-bind:src="c" height="50" />
</li>
</ul>
</div>
</div>
<div>
<canvas id="canvas" height="200" width="200"></canvas>
</div>
<template v-slot:footer>
<button
type="button"
@click="$emit('close')"
class="btn btn-default"
data-dismiss="modal"
>Close</button>
<button type="button" class="btn btn-primary">SCAN</button>
</template>
</modal>
</div>
</template>
<script>
import { getAPI } from "../../axios-api";
import Modal from "../../components/Modal.vue";
export default {
components: { Modal },
data: () => ({
showModal: false,
video: {},
canvas: {},
captures: []
}),
mounted() {
this.initVideo();
},
methods: {
initVideo() {
this.video = this.$refs.video;
if (
"mediaDevices" in navigator &&
"getUserMedia" in navigator.mediaDevices
) {
// const streamElem = document.getElementById('stream').appendChild('video')
navigator.mediaDevices.getUserMedia({ video: true }).then(stream => {
const videoPlayer = document.querySelector("video");
videoPlayer.srcObject = stream;
videoPlayer.play();
});
console.log("init...");
} else {
alert("Livestream currently unavailable.");
}
},
capture() {
this.canvas = this.$refs.canvas;
// this.canvas = document.querySelector("canvas");
// this.canvas = document.getElementById("galleryCanvas");
var context = this.canvas.getContext("2d");
context.drawImage(this.video, 0, 0, 640, 480);
this.captures.push(this.canvas.toDataURL("image/png"));
}
}
};
</script>
解决方案
模型绑定到 showModal 变量。模型仅在此值为 true 时出现,但默认情况下该值设置为 false。因此,在将任何元素附加到模态之前,您必须先将此值设置为 true。
if(your condition is true){
this.showModal = true;
// write further logic to append the video element
}
推荐阅读
- java - 尝试登录时 Firebase.AuthSateListener 未运行
- ffmpeg - 必须至少指定一个输出文件,错误消息问题
- java - 即使 xpath 位于检查中,运行时也会出现 no such element 的错误
- mongodb - MongoDB Kafka 连接器未生成带有 Mongo 文档 ID 的消息密钥
- clickhouse - 如何在 clickhouse 中设置副本和分片?
- vuejs2 - VueJS State Getter 正在寻找匹配项,但未返回正确的值
- java - 使用格式说明符
- android - 空文档的 Android Firestore id
- java - 仅在 CLI 上的单元测试中无法在 src/main/resources 中找到 xsd
- iot - 总是从服务器获得 -1 连接被拒绝响应