context
Я в настоящее время строю библиотеку для точной записи (в идеале любого) анимации на основе JavaScript, даже на медленных компьютерах или в очень высокой кадре (например, 120fps, чтобы сделать размытие движения позже…). До сих пор я сделал переопределение всех основных функций (например, requestAnimationFrame , settimeout , performance.now …) как window.date.prototype.gettime = funct Тайм -аут запланировано намного позже), следующим (и простираются на CSS), что делается в ccapture.js (я удивлен, как эта техника до сих пор хорошо работает).
Теперь моя цель - также иметь дело с видео и аудио. На данный момент давайте сосредоточимся на видео. Для видео одна важная проблема заключается в том, что поиск видео через myVideo.currenttime = foo не является кадром (все браузеры когда-нибудь случайным образом отключаются на несколько кадров), поэтому я бы хотел вместо этого зацепить , чтобы заменить отображаемый контент с помощью фиксированного кадра, например, через веб-кодек. /> возможно ли программно перезаписать элемент так, чтобы:
[*] Я могу добавить такой метод, как myvideo.setcontent (mybuffer) , где MyBuffer - это буфер/canvas, содержащий фрейм, который я на самом деле хочу показывать. Я попытался реализовать это с помощью Shadow Root, но кажется, что видео не совместимы с этим (по крайней мере, я получаю ошибку, когда я пытаюсь…)? В идеале, я хотел бы избежать таких решений, как замена
на, например, Canvas, как пользовательская анимация может внутренне запуска/остановки, перечисляя все теги , и было бы утомительно адаптировать код, когда новое видео добавлено/снято и т. Д. Так что это не совместимо с моим вторым требованием: Обратите внимание, что в конце концов, моя библиотека использует ученика, поэтому, если необходимо, я даже могу себе представить, что я полагаюсь на расширения браузера, чтобы сделать это вместо простого JS, даже если я бы хотел, чтобы это оставалось в браузере-агсе. Обратите внимание, что в идеале вы должны не изменять что -либо, кроме первого (на данный момент пустого) , чтобы проиллюстрировать тот факт, что это решение должно работать без изменения анимации, определенной пользователем.
three.js webgl - materials - video
// We should ideally only overwrite here the components to play it differently
// Ideally, both the standalone video and the threejs video should show
// (up to the webgl added effects) the same frame, that is generated from, e.g.,
// a canvas with something like:
// var c = document.createElement("canvas");
// var ctx = c.getContext("2d");
// ctx.beginPath();
// ctx.arc(95, 50, 40, 0, 2 * Math.PI);
// ctx.stroke();
Play
three.js - webgl video demo
playing sintel trailer
Original video:
Threejs video:
{
"imports": {
"three": "https://cdn.jsdelivr.net/npm/[email protected] ... .module.js",
"three/addons/": "https://cdn.jsdelivr.net/npm/[email protected] ... mples/jsm/"
}
}
import * as THREE from 'three';
import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
import { BloomPass } from 'three/addons/postprocessing/BloomPass.js';
import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
let container;
let camera, scene, renderer;
let video, texture, material, mesh;
let composer;
let mouseX = 0;
let mouseY = 0;
let windowHalfX = window.innerWidth / 2;
let windowHalfY = window.innerHeight / 2;
let cube_count;
const meshes = [],
materials = [],
xgrid = 20,
ygrid = 10;
const startButton = document.getElementById( 'startButton' );
startButton.addEventListener( 'click', function () {
init();
} );
function init() {
const overlay = document.getElementById( 'overlay' );
overlay.remove();
container = document.createElement( 'div' );
document.body.appendChild( container );
camera = new THREE.PerspectiveCamera( 40, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.z = 500;
scene = new THREE.Scene();
const light = new THREE.DirectionalLight( 0xffffff, 3 );
light.position.set( 0.5, 1, 1 ).normalize();
scene.add( light );
renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setAnimationLoop( animate );
container.appendChild( renderer.domElement );
video = document.getElementById( 'video' );
video.play();
video.addEventListener( 'play', function () {
this.currentTime = 3;
} );
texture = new THREE.VideoTexture( video );
texture.colorSpace = THREE.SRGBColorSpace;
//
let i, j, ox, oy, geometry;
const ux = 1 / xgrid;
const uy = 1 / ygrid;
const xsize = 480 / xgrid;
const ysize = 204 / ygrid;
const parameters = { color: 0xffffff, map: texture };
cube_count = 0;
for ( i = 0; i < xgrid; i ++ ) {
for ( j = 0; j < ygrid; j ++ ) {
ox = i;
oy = j;
geometry = new THREE.BoxGeometry( xsize, ysize, xsize );
change_uvs( geometry, ux, uy, ox, oy );
materials[ cube_count ] = new THREE.MeshLambertMaterial( parameters );
material = materials[ cube_count ];
material.hue = i / xgrid;
material.saturation = 1 - j / ygrid;
material.color.setHSL( material.hue, material.saturation, 0.5 );
mesh = new THREE.Mesh( geometry, material );
mesh.position.x = ( i - xgrid / 2 ) * xsize;
mesh.position.y = ( j - ygrid / 2 ) * ysize;
mesh.position.z = 0;
mesh.scale.x = mesh.scale.y = mesh.scale.z = 1;
scene.add( mesh );
mesh.dx = 0.001 * ( 0.5 - Math.random() );
mesh.dy = 0.001 * ( 0.5 - Math.random() );
meshes[ cube_count ] = mesh;
cube_count += 1;
}
}
renderer.autoClear = false;
document.addEventListener( 'mousemove', onDocumentMouseMove );
// postprocessing
const renderPass = new RenderPass( scene, camera );
const bloomPass = new BloomPass( 1.3 );
const outputPass = new OutputPass();
composer = new EffectComposer( renderer );
composer.addPass( renderPass );
composer.addPass( bloomPass );
composer.addPass( outputPass );
//
window.addEventListener( 'resize', onWindowResize );
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
composer.setSize( window.innerWidth, window.innerHeight );
}
function change_uvs( geometry, unitx, unity, offsetx, offsety ) {
const uvs = geometry.attributes.uv.array;
for ( let i = 0; i < uvs.length; i += 2 ) {
uvs[ i ] = ( uvs[ i ] + offsetx ) * unitx;
uvs[ i + 1 ] = ( uvs[ i + 1 ] + offsety ) * unity;
}
}
function onDocumentMouseMove( event ) {
mouseX = ( event.clientX - windowHalfX );
mouseY = ( event.clientY - windowHalfY ) * 0.3;
}
//
let h, counter = 1;
function animate() {
const time = Date.now() * 0.00005;
camera.position.x += ( mouseX - camera.position.x ) * 0.05;
camera.position.y += ( - mouseY - camera.position.y ) * 0.05;
camera.lookAt( scene.position );
for ( let i = 0; i < cube_count; i ++ ) {
material = materials[ i ];
h = ( 360 * ( material.hue + time ) % 360 ) / 360;
material.color.setHSL( h, material.saturation, 0.5 );
}
if ( counter % 1000 > 200 ) {
for ( let i = 0; i < cube_count; i ++ ) {
mesh = meshes[ i ];
mesh.rotation.x += 10 * mesh.dx;
mesh.rotation.y += 10 * mesh.dy;
mesh.position.x -= 150 * mesh.dx;
mesh.position.y += 150 * mesh.dy;
mesh.position.z += 300 * mesh.dx;
}
}
if ( counter % 1000 === 0 ) {
for ( let i = 0; i < cube_count; i ++ ) {
mesh = meshes[ i ];
mesh.dx *= - 1;
mesh.dy *= - 1;
}
}
counter ++;
renderer.clear();
composer.render();
}
Подробнее здесь: https://stackoverflow.com/questions/795 ... d-frame-we
Перезапись видео элемент: отображать другое изображение (вручную декодированную кадр) и совместимость WebGL ⇐ Javascript
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
WxPython - Панель не покрывает весь отображаемый кадр, если кадр полноэкранный
Anonymous » » в форуме Python - 0 Ответы
- 32 Просмотры
-
Последнее сообщение Anonymous
-