Image resizing causing slow scrolling

前端 未结 4 1982
温柔的废话
温柔的废话 2020-12-24 14:00

I\'m loading large images and having the browser resize them. I\'m explicitly setting the size.



        
4条回答
  •  天命终不由人
    2020-12-24 14:41

    This function will permit you to resize an image only once, by replacing it with a new image resized at the desired scale :

    function resizeImage(image, maxWidth, maxHeight) {
    
      // Output scale is the minimum of the two possible scales
      var scale = Math.min((maxWidth / image.width), (maxHeight / image.height))
    
      // Output canvas
      var outputCanvas = document.createElement('canvas')
      outputCanvas.width = image.width * scale
      outputCanvas.height = image.height * scale
    
      // Draw image content in output canvas
      var outputContext = outputCanvas.getContext('2d')
      outputContext.drawImage(image, 0, 0, parseInt(image.width * scale), parseInt(image.height * scale))
    
      // Replace image source
      image.src = outputCanvas.toDataURL()
    }
    

    It takes the image you pass as image parameter, and creates a canvas where it resizes image, and then sets the image.src attribute to the content of the output canvas, using toDataURL().

    Images you resize have to be in RELATIVE path (yes it's not cool), or you will have security error due to CORS if not fulfilled.

    But you can pass base64 data as src attribute, and it can be easy to do it with AJAX.

提交回复
热议问题