2

我正在尝试从哪里上传图像,当用户从磁盘浏览图像时,缩放后的图像在画布上显示为预览。要从画布中获取缩放图像,dataurl 图像仅显示一半图像。当我尝试右键单击并从画布查看图像时,我得到了完整的图像 url。这是我的代码。

<html>
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$('#fileupload').change(function(){
        var MAX_WIDTH = 180;
        var MAX_HEIGHT = 120;

        var file = this.files[0];
        var canvas = document.getElementById('canvas');

        var img = document.createElement("img");

        var reader = new FileReader();

        reader.onload = function(e) {
            img.src = e.target.result;
        }

        img.onload = function(){
            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;
            var ctx = canvas.getContext("2d");
            ctx.scale(1,1);
            ctx.drawImage(img, 0, 0, width, height);

            dataurl = canvas.toDataURL("image/png");
            alert(dataurl); //this path shows imcomplete image.

        }
        reader.readAsDataURL(file);
</script>
</head>
<body>
<input id="fileupload" type="file">
<canvas width="180" height="120" id="canvas"></canvas>
</body>
</html>
4

0 回答 0