Javascript 相机切换不切换
Javascript Camera toggle not toggling
我想将相机 (facingMode
) 从 user
切换到 environment
。在 front
从 true 切换到 false 的意义上,切换似乎是有效的。但是,constraints
中的 facingMode
仍然是 environment
。
我忽略了什么?
代码笔:https://codepen.io/abenjamin/pen/qYWeXj?editors=1111
var front = false;
document.getElementById('cameraToggle').onclick = function() { front = !front; console.log(constraints) };
var constraints = { video: { facingMode: (front? "user" : "environment") } };
您在代码笔中将此行重复了两次,一次在顶部,一次在底部:
document.getElementById('cameraToggle').onclick = function() { front = !front; console.log(constraints) };
另一个问题是原语被值引用。如果您有 let x = 3; const obj = { x }; x = 4;
,对象将不会更改 - 它将继续为 { x: 3 }
。
您需要做的是更新 constraints 对象本身,然后继续执行您需要对变异对象执行的任何操作。例如:
document.getElementById('cameraToggle').onclick = function() {
front = !front;
constraints.video.facingMode = front
? "user"
: "environment";
// interact with the mutated `constraints` object if needed
};
我想将相机 (facingMode
) 从 user
切换到 environment
。在 front
从 true 切换到 false 的意义上,切换似乎是有效的。但是,constraints
中的 facingMode
仍然是 environment
。
我忽略了什么?
代码笔:https://codepen.io/abenjamin/pen/qYWeXj?editors=1111
var front = false;
document.getElementById('cameraToggle').onclick = function() { front = !front; console.log(constraints) };
var constraints = { video: { facingMode: (front? "user" : "environment") } };
您在代码笔中将此行重复了两次,一次在顶部,一次在底部:
document.getElementById('cameraToggle').onclick = function() { front = !front; console.log(constraints) };
另一个问题是原语被值引用。如果您有 let x = 3; const obj = { x }; x = 4;
,对象将不会更改 - 它将继续为 { x: 3 }
。
您需要做的是更新 constraints 对象本身,然后继续执行您需要对变异对象执行的任何操作。例如:
document.getElementById('cameraToggle').onclick = function() {
front = !front;
constraints.video.facingMode = front
? "user"
: "environment";
// interact with the mutated `constraints` object if needed
};