如何用HTML/CSS/JS旋转ESP32-CAM流媒体视频?
ESP32-CAM 视频流旋转功能修复方案
问题根源
你的代码存在两个核心问题:
- JS语法错误:
view:transform.rotation(rot_value)不是合法的JavaScript语法,无法设置元素旋转 - 缺少事件监听:仅获取了初始的选择值,但没有监听下拉框的变化,无法实时更新旋转角度
修复后的完整代码
CSS 部分(新增旋转容器适配)
@media (min-width: 800px) and (orientation:landscape) { #content { display:flex; flex-wrap: nowrap; align-items: stretch } figure img { z-index: 0; display: block; max-width: 100%; max-height: calc(100vh - 40px); /* 添加旋转原点,避免元素偏移 */ transform-origin: center center; transition: transform 0.3s ease; } } /* 通用旋转容器样式,适配旋转后的布局 */ #stream-container { overflow: hidden; display: inline-block; }
HTML 部分(保留原结构)
<div class="input-group" id="rotation-group"> <label for="rotation">Rotation</label> <select id="rotation" class="default-action"> <option value="0" selected="selected">0°</option> <option value="90deg">90°</option> <option value="180deg">180°</option> <option value="-90deg">-90°</option> </select> </div>
JS 部分(核心修复)
document.addEventListener('DOMContentLoaded', function (event) { const view = document.getElementById('stream') const viewContainer = document.getElementById('stream-container') const rotationSelect = document.getElementById('rotation') const startStream = () => { view.src = `${streamUrl}/stream` show(viewContainer) streamButton.innerHTML = 'Stop Stream' // 启动流后应用初始旋转值 updateRotation(rotationSelect.value) } const stopStream = () => { window.stop(); streamButton.innerHTML = 'Start Stream' } // 定义旋转更新函数 const updateRotation = (angle) => { // 正确设置CSS transform属性 view.style.transform = `rotate(${angle})` // 适配90/-90度旋转的容器尺寸,避免内容截断 if (angle === '90deg' || angle === '-90deg') { viewContainer.style.width = view.clientHeight + 'px' viewContainer.style.height = view.clientWidth + 'px' } else { viewContainer.style.width = 'auto' viewContainer.style.height = 'auto' } } // 监听下拉框变化,实时更新旋转 rotationSelect.addEventListener('change', function() { updateRotation(this.value) }) // 页面加载时应用默认旋转值 updateRotation(rotationSelect.value) })
关键修改说明
- 修正旋转语法:使用
element.style.transform = rotate(${angle})标准方式设置元素旋转 - 添加事件监听:为下拉框绑定
change事件,用户切换选项时实时更新旋转角度 - 适配旋转布局:针对90/-90度旋转调整容器尺寸,避免视频内容被截断
- 初始值应用:页面加载和启动流时都应用默认旋转角度,确保初始状态正确
内容的提问来源于stack exchange,提问作者user3635160
相关产品推荐
相关产品推荐

