画布到todataurl没有得到完整的图像

时间:2013-09-07 07:17:58

标签: javascript jquery html5 canvas html5-canvas

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

<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>

0 个答案:

没有答案