Jump to content

POWERED BY:

erissonamorim

Usar câmera traseira do celular

Recommended Posts

Olá pessoal, tudo certo?!

Estou com um código que está funcionando bem. Mas gostaria de que a câmera traseira do celular fosse a padrão.

Abaixo segue o código, caso possam me ajudar a efetuar esta alteração.

Desde já, agradeço!

(function () {
    var video = document.querySelector('video');

    var pictureWidth = 640;
    var pictureHeight = 360;

    var fxCanvas = null;
    var texture = null;

    function checkRequirements() {
        var deferred = new $.Deferred();

        //Check if getUserMedia is available
        if (!Modernizr.getusermedia) {
            deferred.reject('Your browser doesn\'t support getUserMedia (according to Modernizr).');
        }

        //Check if WebGL is available
        if (Modernizr.webgl) {
            try {
                //setup glfx.js
                fxCanvas = fx.canvas();
            } catch (e) {
                deferred.reject('Sorry, glfx.js failed to initialize. WebGL issues?');
            }
        } else {
            deferred.reject('Your browser doesn\'t support WebGL (according to Modernizr).');
        }

        deferred.resolve();

        return deferred.promise();
    }

    function searchForRearCamera() {
        var deferred = new $.Deferred();

        //MediaStreamTrack.getSources seams to be supported only by Chrome
        if (MediaStreamTrack && MediaStreamTrack.getSources) {
            MediaStreamTrack.getSources(function (sources) {
                var rearCameraIds = sources.filter(function (source) {
                    return (source.kind === 'video' && source.facing === 'environment');
                }).map(function (source) {
                    return source.id;
                });

                if (rearCameraIds.length) {
                    deferred.resolve(rearCameraIds[0]);
                } else {
                    deferred.resolve(null);
                }
            });
        } else {
            deferred.resolve(null);
        }

        return deferred.promise();
    }

    function setupVideo(rearCameraId) {
        var deferred = new $.Deferred();
        var videoSettings = {
            video: {
                optional: [
                    {
                        width: { min: pictureWidth }
                    },
                    {
                        height: { min: pictureHeight }
                    }
                ]
            }
        };

        //if rear camera is available - use it
        if (rearCameraId) {
            videoSettings.video.optional.push({
                sourceId: rearCameraId
            });
        }

        navigator.mediaDevices.getUserMedia(videoSettings)
            .then(function (stream) {
                //Setup the video stream
                video.srcObject = stream;

                video.addEventListener("loadedmetadata", function (e) {
                    //get video width and height as it might be different than we requested
                    pictureWidth = this.videoWidth;
                    pictureHeight = this.videoHeight;

                    if (!pictureWidth && !pictureHeight) {
                        //firefox fails to deliver info about video size on time (issue #926753), we have to wait
                        var waitingForSize = setInterval(function () {
                            if (video.videoWidth && video.videoHeight) {
                                pictureWidth = video.videoWidth;
                                pictureHeight = video.videoHeight;

                                clearInterval(waitingForSize);
                                deferred.resolve();
                            }
                        }, 100);
                    } else {
                        deferred.resolve();
                    }
                }, false);
            }).catch(function () {
                deferred.reject('There is no access to your camera, have you denied it?');
            });

        return deferred.promise();
    }

    function step1() {
        checkRequirements()
            .then(searchForRearCamera)
            .then(setupVideo)
            .done(function () {
                //Enable the 'take picture' button
                $('#takePicture').removeAttr('disabled');
                //Hide the 'enable the camera' info
                $('#step1 figure').removeClass('not-ready');
            })
            .fail(function (error) {
                showError(error);
            });
    }

    function step2() {
        var canvas = document.querySelector('#step2 canvas');
        var img = document.querySelector('#step2 img');

        //setup canvas
        canvas.width = pictureWidth;
        canvas.height = pictureHeight;

        var ctx = canvas.getContext('2d');

        //draw picture from video on canvas
        ctx.drawImage(video, 0, 0);

        //modify the picture using glfx.js filters
        texture = fxCanvas.texture(canvas);
        fxCanvas.draw(texture)
            .hueSaturation(-1, -1)//grayscale
            .unsharpMask(20, 2)
            .brightnessContrast(0.2, 0.9)
            .update();

        window.texture = texture;
        window.fxCanvas = fxCanvas;

        $(img)
            //setup the crop utility
            .one('load', function () {
                if (!$(img).data().Jcrop) {
                    $(img).Jcrop({
                        onSelect: function () {
                            //Enable the 'done' button
                            $('#adjust').removeAttr('disabled');
                        }
                    });
                } else {
                    //update crop tool (it creates copies of <img> that we have to update manually)
                    $('.jcrop-holder img').attr('src', fxCanvas.toDataURL());
                }
            })
            //show output from glfx.js
            .attr('src', fxCanvas.toDataURL());
    }

    function step3() {
        var canvas = document.querySelector('#step3 canvas');
        var step2Image = document.querySelector('#step2 img');
        var cropData = $(step2Image).data().Jcrop.tellSelect();

        var scale = step2Image.width / $(step2Image).width();

        //draw cropped image on the canvas
        canvas.width = cropData.w * scale;
        canvas.height = cropData.h * scale;

        var ctx = canvas.getContext('2d');
        ctx.drawImage(
            step2Image,
            cropData.x * scale,
            cropData.y * scale,
            cropData.w * scale,
            cropData.h * scale,
            0,
            0,
            cropData.w * scale,
            cropData.h * scale);

        var spinner = $('.spinner');
        spinner.show();
        $('blockquote p').text('');
        $('blockquote footer').text('');

        // do the OCR!
        Tesseract.recognize(ctx).then(function (result) {
            var resultText = result.text ? result.text.trim() : '';

            //show the result
            spinner.hide();
            $('blockquote p').html('&bdquo;' + resultText + '&ldquo;');
            $('blockquote footer').text('(' + resultText.length + ' characters)');
        });
    }

    /*********************************
     * UI Stuff
     *********************************/

    //start step1 immediately
    step1();
    $('.help').popover();

    function changeStep(step) {
        if (step === 1) {
            video.play();
        } else {
            video.pause();
        }

        $('body').attr('class', 'step' + step);
        $('.nav li.active').removeClass('active');
        $('.nav li:eq(' + (step - 1) + ')').removeClass('disabled').addClass('active');
    }

    function showError(text) {
        $('.alert').show().find('span').text(text);
    }

    //handle brightness/contrast change
    $('#brightness, #contrast').on('change', function () {
        var brightness = $('#brightness').val() / 100;
        var contrast = $('#contrast').val() / 100;
        var img = document.querySelector('#step2 img');

        fxCanvas.draw(texture)
            .hueSaturation(-1, -1)
            .unsharpMask(20, 2)
            .brightnessContrast(brightness, contrast)
            .update();

        img.src = fxCanvas.toDataURL();

        //update crop tool (it creates copies of <img> that we have to update manually)
        $('.jcrop-holder img').attr('src', fxCanvas.toDataURL());
    });

    $('#takePicture').click(function () {
        step2();
        changeStep(2);
    });

    $('#adjust').click(function () {
        step3();
        changeStep(3);
    });

    $('#go-back').click(function () {
        changeStep(2);
    });

    $('#start-over').click(function () {
        changeStep(1);
    });

    $('.nav').on('click', 'a', function () {
        if (!$(this).parent().is('.disabled')) {
            var step = $(this).data('step');
            changeStep(step);
        }

        return false;
    });
})();

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Similar Content

    • By luiz monteiro
      Olá.
      Estou atualizando meu conhecimento com Front-End e me deparei com o seguinte problema.
      Criei um sistema para fazer o upload de imagens e alguns campos text.
      Algo bem simples para depois começar a estudar javascript para mostrar a miniatura....
      Mas quando saio do navegador Chrome ou da aba por mais de 3 minutos, ao retornar o navegador as vezes atualiza ou nem chega atualizar mas limpa os campos.
      Estou usando um Smart Motorola com Android, mas um amigo testou no iPhone e acontece a mesma coisa.
      Gostaria de saber se há como usar javascript para evitar isso?
      Agradeço desde já.

      <!DOCTYPE html>
      <html>
      <head>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1">
          <title>Uploader</title>
      </head>
      <body>
          <form action="?" method="post" enctype="multipart/form-data">
              <br><br>
              <div>selecione a imagem 1</div>
              <input type="file" name="foto1" accept="image/*">
              <br><br>
              <input type="text" name="nome_imagem1">
              
              <br><br>
              <input type="file" name="foto2" accept="image/*">
              <br><br>
              <input type="text" name="nome_imagem2">
              
              <br><br>

              <input type="file" name="foto3" accept="image/*">
              <br><br>
              <input type="text" name="nome_imagem3">
              
              <br><br>
              <input type="submit" value="Enviar">
              <br><br>
          </form>
      <?php
      if ($_SERVER['REQUEST_METHOD'] == 'POST')
      {
          vardump ($_FILES);
      }
      ?>
      </body>
      </html>
       
       
       
    • By belann
      Olá!
       
      Estou usando o nextjs versão 15.2.3 e criei uma navbar que quando é carregado o programa aparece com a home, mas na hora de clicar na página produtos desaparece a navbar.
      A navbar esta sendo chamada no layout.tsx estou usando typescript
      e fica dessa forma
      <div>           <Navbar/>             <main>{children}</main>             </div>  
    • By violin101
      Caros amigos, saudações.

      Estou com uma dúvida, referente cálculo de valores em tempo real.

      Tenho uma rotina, que faz o cálculo, o problema é mostrar o resultado.

      Quero mostrar o RESULTADO assim: 0,00  ou  0.00

      Abaixo posto o código.
      jQuery('input').on('keyup',function(){ //Remover ponto e trocar a virgula por ponto var m = document.getElementById("pgRest").value; while (m.indexOf(".") >= 0) { m = m.replace(".", ""); } m = m.replace(",","."); //Remover ponto e trocar a virgula por ponto var j = document.getElementById("pgDsct").value; while (j.indexOf(".") >= 0) { j = j.replace(".", ""); } j = j.replace(",","."); m = parseFloat(jQuery('#pgRest').val() != '' ? jQuery('#pgRest').val() : 0); j = parseFloat(jQuery('#pgDsct').val() != '' ? jQuery('#pgDsct').val() : 0); //Mostra o Resultado em Tempo Real jQuery('#pgTroco').val(m - j); <<=== aqui estou errando })  
       
      Grato,
       
      Cesar
       
       
    • By violin101
      Caro amigos, saudações.

      Tenho uma tabela escrita em JS que funciona corretamente.
       
      Minha dúvida:
      - como devo fazer para quando a Tabela HTML estiver vazia, exibir o LOGO da Empresa ?

      Abaixo posto o script:
      document.addEventListener( 'keydown', evt => { if (!evt.ctrlKey || evt.key !== 'i' ) return;// Não é Ctrl+A, portanto interrompemos o script evt.preventDefault(); //Chama a Função Calcular Qtde X Valor Venda calcvda(); var idProdutos = document.getElementById("idProdutos").value; var descricao = document.getElementById("descricao").value; var prd_unid = document.getElementById("prd_unid").value; var estoque_atual = document.getElementById("estoque_atual").value; var qtde = document.getElementById("qtde").value; var vlrunit = document.getElementById("vlrunit").value; var vlrtotals = document.getElementById("vlrtotal").value; var vlrtotal = vlrtotals.toLocaleString('pt-br', {minimumFractionDigits: 2}); if(validarConsumo(estoque_atual)){ //Chama a Modal com Alerta. $("#modal_qtdemaior").modal(); } else { if(qtde == "" || vlrunit == "" || vlrtotal == ""){ //Chama a Modal com Alerta. $("#modal_quantidade").modal(); } else { //Monta a Tabela com os Itens html = "<tr style='font-size:13px;'>"; html += "<td width='10%' height='10' style='text-align:center;'>"+ "<input type='hidden' name='id_prds[]' value='"+idProdutos+"'>"+idProdutos+"</td>"; html += "<td width='47%' height='10'>"+ "<input type='hidden' name='descricao[]' value='"+descricao+"'>"+descricao+ "<input type='hidden' name='esp[]' value='"+prd_unid+"'> - ESP:"+prd_unid+ "<input type='hidden' name='estoq[]' value='"+estoque_atual+"'></td>"; html += "<td width='10%' height='10' style='text-align:center;'>"+ "<input type='hidden' name='qtde[]' value='"+qtde+"'>"+qtde+"</td>"; html += "<td width='12%' height='10' style='text-align:right;'>"+ "<input type='hidden' name='vlrunit[]' value='"+vlrunit+"'>"+vlrunit+"</td>"; html += "<td width='14%' height='10' style='text-align:right;'>"+ "<input type='hidden' name='vlrtotal[]' value='"+vlrtotal+"'>"+vlrtotal+"</td>"; html += "<td width='12%' height='10' style='text-align:center;'>"+ "<button type='button' class='btn btn-uvas btn-remove-produto' style='margin-right:1%; padding:1px 3px; font-size:12px;' title='Remover Item da Lista'>"+ "<span class='fa fa-minus' style='font-size:12px;'></span></button></td>"; html += "</tr>"; $("#tbventas tbody").append(html); //Função para Somar os Itens do Lançamento somar(); $("#idProdutos").val(null); $("#descricao").val(null); $("#prd_unid").val(null); $("#qtde").val(null); $("#vlrunit").val(null); $("#vlrtotal").val(null); $("#idProdutos").focus(); //Se INCLUIR NOVO produto - Limpa a Forma de Pagamento $("#pgSoma").val(null); $("#pgRest").val(null); $("#pgDsct").val(null); $("#pgTroco").val(null); $("#tbpagar tbody").empty(); }//Fim do IF-qtde }//Fim do Validar Consumo });//Fim da Função btn-agregar  
      Grato,

      Cesar
       
    • By violin101
      Caros amigos, saudações.

      Estou com uma pequena dúvida se é possível ser realizado.

      Preciso passar 2 IDs para o Sistema executar a função, estou utilizando desta forma e gostaria de saber como faço via JS para passar os parâmetro que preciso.

      Observação:
      Dentro da TABELA utilizei 2 Forms, para passar os IDS que preciso, funcionou conforme código abaixo.
      <div class="card-body"> <table id="tab_clie" class="table table-bordered table-hover"> <thead> <tr> <th style="text-align:center; width:10%;">Pedido Nº</th> <th style="text-align:center; width:10%;">Data Pedido</th> <th style="text-align:center; width:32%;">Fornecedor</th> <th style="text-align:center; width:10%;">Status</th> <th style="text-align:center; width:5%;">Ação</th> </tr> </thead> <tbody> <?php foreach ($results as $r) { $dta_ped = date(('d/m/Y'), strtotime($r->dataPedido)); switch ($r->pd_status) { case '1': $status = '&nbsp;&nbsp;Aberto&nbsp;&nbsp;'; $txt = '#FFFFFF'; //Cor: Branco $cor = '#000000'; //Cor: Preta break; case '2': $status = 'Atendido Total'; $txt = '#FFFFFF'; //Cor: Branco $cor = '#086108'; //Cor: Verde break; case '3': $status = 'Atendido Parcial'; $txt = '#000000'; //Cor: Branco $cor = '#FEA118'; //Cor: Amarelo break; default: $status = 'Cancelado'; $txt = '#FFFFFF'; //Cor: Branco $cor = '#D20101'; //Cor: Vermelho break; } echo '<tr>'; echo '<td width="10%" height="10" style="text-align:center;">'.$r->pd_numero.'</td>'; echo '<td width="10%" height="10" style="text-align:center;">'.$dta_ped.'</td>'; echo '<td width="32%" height="10" style="text-align:left;">'.$r->nome.'</td>'; echo '<td width="10%" height="10" style="text-align:left;"><span class="badge" style="color:'.$txt.'; background-color:'.$cor.'; border-color:'.$cor.'">'.$status.'</span></td>'; echo '<td width="5%" style="text-align:center;">'; ?> <div class="row"> <?php if($this->permission->checkPermission($this->session->userdata('permissao'), 'vPedido')){ ?> <form action="<?= base_url() ?>compras/pedidos/visualizar" method="POST" > <input type="hidden" name="idPedido" value="<?php echo $r->idPedidos; ?>"> <input type="hidden" name="nrPedido" value="<?php echo $r->pd_numero; ?>"> <button class="btn btn-warning" title="Visualizar" style="margin-left:50%; padding: 1px 3px;"><i class="fa fa-search icon-white"></i></button> </form> <?php } if($this->permission->checkPermission($this->session->userdata('permissao'), 'ePedido')){ ?> <form action="<?= base_url() ?>compras/pedidos/editar" method="POST" > <input type="hidden" name="idPedido" value="<?php echo $r->idPedidos; ?>"> <input type="hidden" name="nrPedido" value="<?php echo $r->pd_numero; ?>"> <button class="btn btn-primary" title="Editar" style="margin-left:50%; padding: 1px 3px;"><i class="fa fa-edit icon-white"></i></button> </form> <?php } ?> </div> <?php echo '</td>'; echo '</tr>'; } ?> </tbody> </table> </div>
      Grato,

      Cesar.
×

Important Information

Ao usar o fórum, você concorda com nossos Terms of Use.