gpt4 book ai didi

javascript - 在 React Konva 中在 Canvas 上播放视频

转载 作者:行者123 更新时间:2023-12-04 10:45:03 52 4
gpt4 key购买 nike

建筑关闭 Konva关于如何将视频渲染到 Canvas 的文档,我想通过直接从 Konva.Image 访问视频引用来播放视频。实例。下面是一个人为的示例,用于模拟我从​​组件外部动态播放视频的目标。即使 imageRef.current.image(),以下内容也没有按预期播放视频返回视频元素引用。关于如何访问视频引用的任何建议?

import React, { useEffect, useContext, useState } from 'react'
import { Image } from "react-konva";
import Konva from 'konva'

export const MainVideo = ({ shape, dispatch }) => {
const imageRef = React.useRef(null);
const video = document.createElement('video');
video.setAttribute('src',shape.url);


useEffect(() => {
if(imageRef) {

imageRef.current.image().play();
const layer = imageRef.current.getLayer();

const anim = new Konva.Animation(() => {
}, layer);

anim.start()

}
}, [imageRef])

return (
<Image
ref={imageRef}
opacity={shape.o}
id={shape.id}
image={video}
x={shape.x}
y={shape.y}
zIndex={0}
height={360}
width={640} />
)
}

最佳答案

你可以这样做:

const Video = ({ src }) => {
const imageRef = React.useRef(null);
const [size, setSize] = React.useState({ width: 50, height: 50 });

// we need to use "useMemo" here, so we don't create new video elment on any render
const videoElement = React.useMemo(() => {
const element = document.createElement("video");
element.src = src;
return element;
}, [src]);

// when video is loaded, we should read it size
React.useEffect(() => {
const onload = function() {
setSize({
width: videoElement.videoWidth,
height: videoElement.videoHeight
});
};
videoElement.addEventListener("loadedmetadata", onload);
return () => {
videoElement.removeEventListener("loadedmetadata", onload);
};
}, [videoElement]);

// use Konva.Animation to redraw a layer
React.useEffect(() => {
videoElement.play();
const layer = imageRef.current.getLayer();

const anim = new Konva.Animation(() => {}, layer);
anim.start();

return () => anim.stop();
}, [videoElement]);

return (
<Image
ref={imageRef}
image={videoElement}
x={20}
y={20}
stroke="red"
width={size.width}
height={size.height}
draggable
/>
);
};

演示: https://codesandbox.io/s/react-konva-video-on-canvas-oygvf

关于javascript - 在 React Konva 中在 Canvas 上播放视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59741398/

52 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com