通过画布加载图像和调整大小会导致无限循环

时间:2018-02-02 21:26:42

标签: javascript canvas onload

我希望在加载<input type='file'>上的虚拟点击并通过将其绘制到画布上进行压缩后,正确缩放图像。在console.log()内调用img.onload时,我发现它正在循环中运行。将img.src = canvas.toDataURL("image/png")放在onload之外导致空白图像但没有循环。通过反复试验移动事物并没有效果,因为我没有在这里获得动态(即使我可以在重新缩放画布时重新绘制图像)。谢谢!

$('button.picture').on('click',function(){
        var outerWrapper = $(this).closest('.outerWrapper')
        $(this).siblings('.imageLoad').on('change', function(e){
            var loadedImage = e.target.files[0]
            var img = new Image();
            img.src = window.URL.createObjectURL(loadedImage);
            var canvas = document.createElement("canvas");
            canvas.width = outerWrapper.width()
            canvas.height = outerWrapper.height()
            img.onload = function(e){
                //still here the img.width returns the canvas width and not the original image's width
                console.log(img.width)
                var context = canvas.getContext("2d");
                context.drawImage(img,0,0, canvas.width, canvas.height )
                img.src = canvas.toDataURL("image/png")
            }
      $(this).closest('.outerWrapper').children('.imageWrapper').append(img)
        })
    $(this).siblings('.imageLoad').trigger('click')
})

1 个答案:

答案 0 :(得分:0)

要回答我自己的问题,我想说清楚我的目标是什么:

  1. 通过虚拟点击<input type="file">
  2. 加载图片
  3. 保持原始图像的宽高比
  4. 压缩它
  5. 有效的方法是设置img.src = canvas.toDataURL("image/png"),就像调整画布大小时一样,但是再次使用URL.createObjectURL(loadedImage)加载原始图像。为了保持纵横比,我必须创建两个单独的图像,一个用于计算img.naturalWidthimg.naturalHeight,另一个用于将图像加载到画布上。有魅力。有兴趣了解它可以在哪里完善。

    $('button.picture').on('click',function(){
        var outerWrapper = $(this).closest('.outerWrapper')
    
        $(this).siblings('.imageLoad').on('change', function(e){
    
            var loadedImage = e.target.files[0]
            var img = new Image();
            img.src = window.URL.createObjectURL(loadedImage);
    
            var canvasPic = $('<canvas class="canvasPic"></canvas>')
            canvasPic.prependTo(outerWrapper)
    
            var canvas = canvasPic[0]
            canvas.width = outerWrapper.width()
            canvas.height = outerWrapper.height()
            var context = canvas.getContext("2d");
    
            var image = new Image();
            image.onload = function(){
                var w = img.naturalWidth
                var h = img.naturalHeight
                var ratio = h/w
                var newWidth = canvas.height/ratio
                context.drawImage(img,0,0,newWidth,canvas.height)
            }
            image.src = URL.createObjectURL(loadedImage);
        })
        $(this).siblings('.imageLoad').trigger('click')
    })