javascript - 图像大小调整在 Chrome 中有效,但在 Firefox 中无效

标签 javascript angularjs

我的 Angular 1.5 应用程序中有一个函数可以在 base64 编码的图像超过最大尺寸时调整其大小。此函数在 Chrome 中运行良好,但在 Firefox 中它返回一个空字符串而不是任何 base64 编码的字符串。

I've got it packaged up in an Angular app in Plunker here,但这是相关的功能:

  // Image resizing
  $scope.resizeImage = function(base64Data, maxWidth, maxHeight) {
    img = document.createElement('img');

    img.src = base64Data;
    height = img.height;
    width = img.width;

    if (width > maxWidth) {
      ratio = maxWidth / width; // get ratio for scaling image
      height = height * ratio; // Reset height to match scaled image
      width = width * ratio; // Reset width to match scaled image
    }

    // Check if current height is larger than max
    if (height > maxHeight) {
      ratio = maxHeight / height; // get ratio for scaling image
      width = width * ratio; // Reset width to match scaled image
      height = height * ratio; // Reset height to match scaled image
    }

    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');

    // We set the dimensions at the wanted size.
    canvas.width = width;
    canvas.height = height;

    // We resize the image with the canvas method drawImage();
    ctx.drawImage(img, 0, 0, width, height);

    var dataURI = canvas.toDataURL();
    return dataURI;
  }

最佳答案

您可能需要等到 <img>已加载:

img.onload = function() {
    // now your image is ready for use
};

关于javascript - 图像大小调整在 Chrome 中有效,但在 Firefox 中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35759809/

相关文章:

javascript - jquery 上的 validate() 问题

javascript - Jquery 的 nth-child 选择器的语法错误

javascript - jQuery 和 AJAX

angularjs - 如何使用 Angular 从对象中获取变量作为 ng-model

javascript - 未评估的 ng 类

javascript - 即使 Angular 中没有数据,也会显示分页

javascript - Three.js - GLTF 模型位置不是从原点开始

javascript - JSON 到 Tree JS

javascript - Angular 指令模板抛出错误

angularjs - 如何在 Angular ui-grid 之外放置分页?