【问题标题】:KineticJS: Image does not have a Stroke after applying a FilterKineticJS:应用过滤器后图像没有描边
【发布时间】:2014-11-09 22:58:37
【问题描述】:

使用 KineticJS 5.1.0

我有一个带有笔划的 KineticJS 图像。我想对这张图片应用一个过滤器。缓存并应用过滤器后,笔触消失了。

Here is a JSFiddle 和我的演示代码:

var imageObj = new Image();
      imageObj.onload = function() {
        var stage = new Kinetic.Stage({
          container: 'container',
          width: 600,
          height: 700
        });
        var layer = new Kinetic.Layer();
        img = new Kinetic.Image({
          x: 250,
          y: 200,
          image: imageObj,
          draggable: true
        });
        var strokeWidthValue = 10;
        img.setOffsetX(img.getWidth() / 2); 
        img.setOffsetY(img.getHeight() / 2); 
        img.stroke("green");  
        img.strokeWidth(strokeWidthValue);
        img.strokeScaleEnabled(false);  
        img.strokeEnabled(true);  

        layer.add(img);
        stage.add(layer);

        img.cache();
        img.filters([Kinetic.Filters.Invert]);
        layer.draw();
      };
       imageObj.crossOrigin = "anonymous";
      imageObj.src =
  "https://dl.dropboxusercontent.com/u/47067729/darth-vader.jpg";

这是我应用过滤器之前的图像:

在我应用过滤器之后:

如何在应用滤镜后恢复笔触?

编辑:我也尝试为边框添加额外的空间,但结果显示粉红色边框,我的边框应该是绿色的。这是我尝试过的缓存功能:

    img.cache({
        x: -(img.getWidth() / 2) - strokeWidthValue,
        y: -(img.getHeight() / 2) - strokeWidthValue,
        width: img.getWidth() + (strokeWidthValue * 2),
        height: img.getHeight() + (strokeWidthValue * 2)
    });

结果如下:

完整的例子可以在this JSFiddle找到。

【问题讨论】:

    标签: javascript html kineticjs


    【解决方案1】:

    http://jsfiddle.net/truefusion/o73ur6pf/8/

    当我们创建缓存并对图像应用过滤器时,我们可以从Kinetic.Image._cache.canvas.filter 访问结果。然后,我们可以通过在过滤器画布上调用 toDataURL() 将结果转换为数据 URI。为了避免在清除图像缓存时出现问题,我们创建了一个新的图像元素并将数据 URI 分配给它的 src 属性。然后我们使用img.setImage() 将新图像设置为 Kinetic 图像对象。

    var image = new Image()
    ,   data  = img._cache.canvas.filter.toDataURL()
    ;
    
    image.src = data;
    img.setImage(image);
    

    然后您可以安全地清除缓存,将 null 传递给 unload 回调,然后玩得开心!

    您必须考虑笔划的大小。也就是说,在img.cache()属性中,X和Y减去strokeWidth,宽度和高度加上(strokeWidth * 2)。

    【讨论】:

    • 我这样做了,但你可以在这里看到:jsfiddle.net/confile/o73ur6pf 边框颜色不同,不能再移除了。
    • @confile 这是一个可能的解决方案jsfiddle.net/o73ur6pf/5 我所做的是创建一个新的临时文件。层,克隆图像,将其放在临时层并将图像转换为数据 URI,然后替换图像并清除缓存。 (你不需要像我一样的超时。)
    • 在应用过滤器后正确获取图像边框不是有点过重吗?一定有更简单的方法。
    • @confile jsfiddle.net/o73ur6pf/6 我不再需要创建临时层,只使用了图像缓存中的那个。
    • 使用 toImage() 代替 toDataURL() 会更快吗?
    猜你喜欢
    • 2013-05-04
    • 1970-01-01
    • 2021-06-27
    • 2013-07-15
    • 1970-01-01
    • 2021-03-22
    • 2015-06-17
    • 2021-04-08
    • 1970-01-01
    相关资源
    最近更新 更多