Base de conocimientosCentro de exámenes
ESEspañol
Elegir idioma13

CKTIS / HTML

El atributo capture en campos de archivo: user y environment

En un campo de archivo, `capture` indica una preferencia al crear un archivo multimedia. Para fotos y vídeos, `user` prefiere la cámara frontal y `environment` la que apunta hacia el entorno.

Versión: W3C HTML Media Capture Recommendation (2018); implementation support varies

Sintaxis

<input type="file" accept="image/*" capture="user">
<input type="file" accept="image/*" capture="environment">

capture es un atributo de HTML Media Capture que se usa en un input con type="file". Usa accept para indicar el tipo de archivo esperado: image/* para imágenes, video/* para vídeo o audio/* para audio. Sigue siendo un campo de archivo: el atributo no proporciona a la página una secuencia multimedia en directo ni sube el archivo.

Para fotos y vídeos, capture="user" da preferencia a la cámara que apunta hacia la persona, normalmente la frontal. capture="environment" da preferencia a la que apunta hacia el entorno, normalmente la trasera. Especifica el valor: capture sin valor no selecciona ninguna de esas dos orientaciones.

Es una indicación, no una obligación. Si la orientación solicitada no está disponible, el navegador puede usar su modo predeterminado. Según el dispositivo y la compatibilidad del navegador, también puede mostrar un menú o un selector de archivos normal. Si es importante poder elegir un archivo existente, ofrece otro campo sin capture. accept no valida el contenido de los archivos: si se suben a un servidor, valídalos allí.

Ejemplos

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Photo capture preferences</title>
</head>
<body>
  <p>
    <label for="front-photo">Take a selfie (front camera preferred)</label><br>
    <input id="front-photo" type="file" accept="image/*" capture="user">
  </p>
  <p>
    <label for="rear-photo">Take a photo (rear camera preferred)</label><br>
    <input id="rear-photo" type="file" accept="image/*" capture="environment">
  </p>
  <p>
    <label for="image-file">Choose an image file</label><br>
    <input id="image-file" type="file" accept="image/*">
  </p>
  <script>
    const controls = [...document.querySelectorAll('input[type="file"]')];
    const descriptions = new Map([
      ['user', 'requests a front-facing camera'],
      ['environment', 'requests an outward-facing camera'],
      [null, 'makes no capture request']
    ]);
    const expectedPreferences = [...descriptions.keys()];
    const isVisible = element =>
      element.getClientRects().length > 0 &&
      getComputedStyle(element).visibility === 'visible';

    // Check the controls and their markup, not which picker or camera opens.
    if (controls.length !== expectedPreferences.length ||
        !controls.every((control, index) =>
          isVisible(control) &&
          [...control.labels].some(label => isVisible(label) && label.innerText.trim()) &&
          control.accept === 'image/*' &&
          control.getAttribute('capture') === expectedPreferences[index] &&
          !control.form)) {
      throw new Error('Expected three visible, labeled image file controls with the specified capture preferences and no upload form.');
    }

    const [first, second, third] = controls.map(control =>
      descriptions.get(control.getAttribute('capture'))
    );
    console.log(
      'The page displays three labeled image file controls. ' +
      `The first ${first}, the second ${second}, and the third ${third}. ` +
      'The browser and device determine what opens when each control is activated. ' +
      'The page does not upload anything.'
    );
  </script>
</body>
</html>

Resultado

The page displays three labeled image file controls. The first requests a front-facing camera, the second requests an outward-facing camera, and the third makes no capture request. The browser and device determine what opens when each control is activated. The page does not upload anything.

El primer campo prefiere la cámara frontal, el segundo la trasera y el tercero no solicita captura. Compara qué abre cada uno en un móvil y en un ordenador. El ejemplo no sube ningún archivo.

Lecciones relacionadas

  • HTML · Lección 7 · Intermedio · Versión: 2

Fuentes