miércoles, 7 de septiembre de 2016

javascript cargar imagen en un canvas desde input

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script>
//*********************************
window.onload = function()
{
    var input = document.getElementById('fotos');
    input.addEventListener('change', handleFiles);
}

//*********************************
function handleFiles(e)
{
    var ctx = document.getElementById('canvas').getContext('2d');
    var img = new Image;
   
    img.src = URL.createObjectURL(e.target.files[0]);
   
    img.onload = function()
    {
        var MAX_WIDTH = 800;
        var MAX_HEIGHT = 600;
        var width = img.width;
        var height = img.height;

        if (width > height)
        {
            if (width > MAX_WIDTH)
            {
                height *= MAX_WIDTH / width;
                width = MAX_WIDTH;
            }
        }
        else
        {
            if (height > MAX_HEIGHT)
            {
                width *= MAX_HEIGHT / height;
                height = MAX_HEIGHT;
            }
        }

        canvas.width = width;
        canvas.height = height;

        ctx.drawImage(img, 0,0,width, height);
    }
   
   
}




</script>
</head>
<body>
<input type="file" id="fotos" multiple="multiple" />
<br>
<canvas width="400" height="300" id="canvas" style="border: 1px solid #000000;"/>

</body>
</html>

No hay comentarios: