在 Draft.js 中无法垂直调整图像大小

Failed to resize image vertically in Draft.js

我正在使用 Draft.js 插件 Resizeable

我正在尝试使用原始长宽比调整图像大小。

但是,对于下面的代码,当我使用鼠标在图像的底部边缘调整大小时,光标发生了变化,但无法调整大小。它只在左右边缘有效。

const resizeablePlugin = createResizeablePlugin({
  vertical: 'relative',
  horizontal: 'relative'
});

codesandbox

看了source code后,我还是没弄清楚是什么原因造成的。

这个插件的开发者似乎没有提供这个机会,当你通过顶部或底部边缘调整大小时,改变图像大小和保存比例。配置选项 vertical: 'relative' 意味着插件应该以相对单位(百分比)设置 height 值。您可以使用 devtools 检查当您尝试调整图像大小时 height 值确实发生了变化。但是我们应该更改 width 值以达到当我们使用保存比例调整图像大小时的行为。

稍微重写一下源码就可以实现。检查 this fork of your sandbox.

检查 createDecorator.js 它是存储在 /node_modules/draft-js-resizeable-plugin/lib/createDecorator.js 中的同一个文件。我改变了什么?查找 doDrag 函数(我用 // ! 销售所有添加或更改的字符串):

...
var startWidth = parseInt(document.defaultView.getComputedStyle(pane).width, 10);
var startHeight = parseInt(document.defaultView.getComputedStyle(pane).height, 10);

var imageRect = pane.getBoundingClientRect(); // !
var imageRatio = imageRect.width / imageRect.height; // ! get image ratio

// Do the actual drag operation
var doDrag = function doDrag(dragEvent) {
  var width = startWidth + dragEvent.clientX - startX;
  var height = startHeight + dragEvent.clientY - startY;
  var block = store.getEditorRef().refs.editor;
  width = block.clientWidth < width ? block.clientWidth : width;
  height = block.clientHeight < height ? block.clientHeight : height;

  var widthForPercCalculation = (isTop || isBottom) && vertical === 'relative' ? height * imageRatio : width; // ! calculate new width value in percents

  var widthPerc = 100 / block.clientWidth * widthForPercCalculation; // !
  var heightPerc = 100 / block.clientHeight * height;

  var newState = {};
  if ((isLeft || isRight) && horizontal === 'relative') {
    newState.width = resizeSteps ? round(widthPerc, resizeSteps) : widthPerc;
  } else if ((isLeft || isRight) && horizontal === 'absolute') {
    newState.width = resizeSteps ? round(width, resizeSteps) : width;
  }

  if ((isTop || isBottom) && vertical === 'relative') {
    newState.width = resizeSteps ? round(widthPerc, resizeSteps) : widthPerc; // ! here we update width not height value
  } else if ((isTop || isBottom) && vertical === 'absolute') {
    newState.height = resizeSteps ? round(height, resizeSteps) : height;
  }
...

我想你可以要求这个插件开发团队添加这个功能或者 fork 项目。