我有一个视频元素,希望允许用户在画布上绘图,捕获画布流并将其显示在视频元素上,但是视频显示黑屏,我不知道我做错了什么,这是我的代码
const localVideo = document.getElementById('localVideo')
class SignTool {
constructor() {
this.initVars()
this.initEvents()
this.currentColor = "white";
this.resize(this.ctx);
}
initVars() {
this.canvas = this.createCanvas()
this.ctx = this.canvas.getContext("2d")
this.isMouseClicked = false
this.isMouseInCanvas = false
this.prevX = 0
this.currX = 0
this.prevY = 0
this.currY = 0
}
initEvents() {
this.canvas.onmousemove = (e) => {this.onMouseMove(e)}
this.canvas.onmousedown = (e) => this.onMouseDown(e)
this.canvas.onmouseup = () => this.onMouseUp()
this.canvas.onmouseout = () => this.onMouseOut()
this.canvas.onmouseenter = (e) => this.onMouseEnter(e)
let canvasStream = this.canvas.captureStream();
localVideo.srcObject = canvasStream;
localVideo.onloadedmetadata = () => {
localVideo.play();
}
}
onMouseDown(e) {
this.isMouseClicked = true
this.updateCurrentPosition(e)
}
createCanvas() {
const canvasDiv = document.querySelector('.canvas-holder')
// create canvas element and append it to document body
let canvas = document.createElement('canvas');
canvas.id = "canvas"
canvasDiv.appendChild(canvas);
// some hotfixes... ( ≖_≖)
canvas.style.position = 'fixed';
return canvas
}
onMouseUp() {
this.isMouseClicked = false
}
onMouseEnter(e) {
this.isMouseInCanvas = true
this.updateCurrentPosition(e)
}
resize(ctx) {
ctx.canvas.width = localVideo.getBoundingClientRect().width;
ctx.canvas.height = localVideo.getBoundingClientRect().height;
}
onMouseOut() {
this.isMouseInCanvas = false
}
onMouseMove(e) {
if (this.isMouseClicked && this.isMouseInCanvas) {
this.updateCurrentPosition(e)
this.draw()
}
}
updateCurrentPosition(e) {
this.prevX = this.currX
this.prevY = this.currY
this.currX = e.clientX - this.canvas.offsetLeft
this.currY = e.clientY - this.canvas.offsetTop
}
draw() {
this.ctx.beginPath()
this.ctx.moveTo(this.prevX, this.prevY)
this.ctx.lineTo(this.currX, this.currY)
this.ctx.strokeStyle = this.currentColor
this.ctx.lineWidth = 2
this.ctx.stroke()
this.ctx.closePath()
}
}
document.addEventListener('DOMContentLoaded', _ => {
new SignTool()
})
视频显示黑屏,显示控件显然它显示音轨计数但黑屏