javascript - 如何在fabricjs中获取缩放后的图像数据

标签 javascript scale fabricjs

我在图像上应用滤镜,修改每个像素。问题是当我更改图像的比例时,fabricjs 始终将原始图像(比例之前)作为过滤器的输入。然后,我无法修改新数据的每个像素(缩放后)。

有人知道该怎么做吗?太棒了,提前谢谢!!

最佳答案

这样做涉及到您所期望的。没有快捷方式或内置功能可以执行此操作。我创建了一个概念验证 on this fork 。它并不完美 - 缓存被禁用。如果您单击该链接,您会发现该分支是从另一个 POC branch of mine fork 出来的。 。我尝试清理下面的代码。如果我向父项目提交 PR,我将更新此答案。

这些变化主要影响image.class.js的applyFilters函数:

  applyFilters: function(filters) {

  filters = filters || this.filters || [];
  filters = filters.filter(function(filter) { return filter; });
  if (this.group) {
    this.set('dirty', true);
  }
  if (filters.length === 0) {
    this._element = this._originalElement;
    this._filterScalingX = 1;
    this._filterScalingY = 1;
    return this;
  }

  var imgElement = this._scaledEl || this._originalElement,
      sourceWidth = imgElement.naturalWidth || imgElement.width,
      sourceHeight = imgElement.naturalHeight || imgElement.height;

  if (!this._filteredEl || this._filteredEl === this._originalElement) {
    // if the element is the same we need to create a new element
    var canvasEl = fabric.util.createCanvasElement();
    canvasEl.width = sourceWidth;
    canvasEl.height = sourceHeight;
    this._element = canvasEl;
    this._filteredEl = canvasEl;
  }
  else {
    // clear the existing element to get new filter data
    this._element = this._filteredEl;
    this._filteredEl.getContext('2d').clearRect(0, 0, sourceWidth, sourceHeight);
  }

  if (!fabric.filterBackend) {
    fabric.filterBackend = fabric.initFilterBackend();
  }

  fabric.filterBackend.applyFilters(filters, this._originalElement, sourceWidth, sourceHeight, this._element, this.cacheKey);

  if (this._originalElement.width !== this._element.width ||
    this._originalElement.height !== this._element.height) {
    this._filterScalingX = this._element.width / this._originalElement.width;
    this._filterScalingY = this._element.height / this._originalElement.height;
  }
  return this;
},

关于javascript - 如何在fabricjs中获取缩放后的图像数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47753050/

相关文章:

javascript - 如何使用 axios 检测 401 并停止控制台错误

javascript - 无法更改 CSS 中的下拉列表选项高度

javascript - Angular 6 - 如何读取特定于 Angular 属性

python - 如何从 tkinter 比例小部件显示中删除比例值?

javascript - 有没有办法加速 canvas.toDatalessJSON() 函数来保存 Canvas 的历史记录?

javascript - 在 Canvas Fabric JS 中的元素上添加删除按钮

javascript - 关闭 fabricjs 图像对象的缓存

javascript - RXJS5 像 Promise 一样链接

MySQL 向上扩展还是向外扩展?

html - 在 html 和 css 中缩放矩形