如何使p5.js调用的手机摄像头画面实现全屏显示?
解决p5.js在iPhone上摄像头画面无法全屏的问题
iPhone上出现摄像头画面无法铺满全屏,核心原因是手机视口未正确配置、视频流宽高比与画布不匹配,以及浏览器默认页面边距这三点。以下是具体解决步骤:
1. 添加视口元标签
在HTML的<head>中添加视口配置,确保页面完全适配手机屏幕,禁止缩放和滚动:
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
2. 移除页面默认边距
在HTML中添加CSS样式,消除body的默认边距和滚动条:
<style> body { margin: 0; padding: 0; overflow: hidden; } </style>
3. 适配视频流宽高比
摄像头的视频流有固定宽高比,直接拉伸会导致变形或无法铺满。修改draw函数,计算合适的尺寸和偏移量,让画面铺满画布同时保持比例(超出部分会被裁剪):
function draw() { // 计算视频与画布的宽高比 const videoRatio = capture.width / capture.height; const canvasRatio = width / height; let drawW, drawH, x, y; if (videoRatio > canvasRatio) { // 视频更宽,按画布高度铺满,裁剪左右 drawH = height; drawW = drawH * videoRatio; x = (width - drawW) / 2; y = 0; } else { // 视频更高,按画布宽度铺满,裁剪上下 drawW = width; drawH = drawW / videoRatio; x = 0; y = (height - drawH) / 2; } // 绘制铺满画布的摄像头画面 image(capture, x, y, drawW, drawH); // 绘制标签文本 fill(255); text(label, 10, 50); }
4. 优化画布尺寸设置
改用windowWidth和windowHeight替代displayWidth,同时监听窗口大小变化(适配横竖屏切换):
function setup() { createCanvas(windowWidth, windowHeight); // 其他代码不变(约束、捕获摄像头等) } // 横竖屏切换时重新调整画布 function windowResized() { resizeCanvas(windowWidth, windowHeight); }
完整修改后的代码示例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"> <title>Fullscreen Camera</title> <style> body { margin: 0; padding: 0; overflow: hidden; } </style> <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.7.0/p5.min.js"></script> <script src="https://unpkg.com/ml5@latest/dist/ml5.min.js"></script> </head> <body> <script> var capture; let label = "Waiting.."; let classifier; function preload(){ classifier = ml5.imageClassifier('https://teachablemachine.withgoogle.com/models/UO8AXdEl9/'); } function setup() { createCanvas(windowWidth, windowHeight); var constraints = { audio: false, video: { facingMode: { exact: "environment" } } }; capture = createCapture(constraints); capture.hide(); classifyVideo(); } function classifyVideo(){ classifier.classify(capture, gotResults); } function gotResults(error, results){ if(error){ console.error(error); return; } label = results[0].label; classifyVideo(); } function draw() { const videoRatio = capture.width / capture.height; const canvasRatio = width / height; let drawW, drawH, x, y; if (videoRatio > canvasRatio) { drawH = height; drawW = drawH * videoRatio; x = (width - drawW) / 2; y = 0; } else { drawW = width; drawH = drawW / videoRatio; x = 0; y = (height - drawH) / 2; } image(capture, x, y, drawW, drawH); fill(255); text(label, 10, 50); } function windowResized() { resizeCanvas(windowWidth, windowHeight); } </script> </body> </html>
内容的提问来源于stack exchange,提问作者J.vee
相关产品推荐
相关产品推荐

