Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

213
Visualizações
Using canvas to take a picture of an image element

I wanted to take a picture of a photo I have on my webpage using a canvas to get a local url for it. Obviously, this is redundant because I already have the url for the photo, but it would be useful in other contexts (like videos). When I execute this code, a white box appears that is not the image I use for testing purpose. Where am I going wrong here?

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="main.js" defer></script>
</head>
<style>
    img{
        height: 500px;
        width: 500px;
    }
</style>
<body>
    <img id="test" src="img_url">
    <button onclick="takePhoto()">Click Me</button>
</body>
</html>

JS:

var width=200
var height=300
function takePhoto(){
    var test = document.getElementById("test")
    var canvas = document.createElement("canvas")
    document.body.appendChild(canvas)
    var cxt = canvas.getContext('2d');
    canvas.width = width;
    canvas.height = height;
    cxt.drawImage(test, width, height);
    var data = canvas.toDataURL('image/png');
    console.log(data)     
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The 3 params version of drawImage() is

drawImage(source, x, y);

You did set the x and y params to the width and height of the canvas, which means the browser will draw the image from the bottom right corner of the canvas, which obviously doesn't do much.

You probably wanted the 5 params version

drawImage(source, x, y, resizeWidth, resizeHeight);

Where you'd set x and y to 0.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda