2

I'm using Konva.js to do some canvas animations. I have circle shapes, with an image fill, and would like to apply a color overlay/filter to the shape (RGBA).

This is how I'm creating the Shape object:

var konvaObject = new Konva.Circle({
    x: 100,
    y: 100,
    radius: 300,
    stroke: this.color,
    strokeWidth: 6,
    fillPatternRepeat: 'no-repeat',
});

// load the image into the shape:
var imageObj = new Image();
imageObj.onload = function () {
    konvaObject.fillPatternImage(imageObj);
    konvaObject.draw();
}
imageObj.src = 'www.demo.com/anImageName.png';

demo: http://jsbin.com/winugimeme/edit?js,output

The Docs outline an RGBA filter, however as far as I can tell it can only be applied to Konva.Image items.

Is there a way to re-work my above code so that I can apply filters to the shape object/fill image?

tdc
  • 5,174
  • 12
  • 53
  • 102

1 Answers1

2

According to filter documentation, you have to cache shape before applying filters http://konvajs.github.io/api/Konva.Filters.html#RGBA

node.cache();
node.filters([Konva.Filters.RGBA]);
node.blue(120);
node.green(200);
node.alpha(0.3);

Note: jsbin demo will not work with this example as fill image should be CORS enabled (e.g. hosted on same domain).

lavrton
  • 18,973
  • 4
  • 30
  • 63
  • I tried the above and got the aforementioned CORS error. Is there any way to get around the CORS limitation..? I'm loading images from a CDN. I don't really understand why that is a CORS issue when I can link images from the same CDN and get them to load as image tags. Why does manipulating them on canvas cause a CORS error? – tdc Jul 01 '16 at 12:41
  • You can try this trick to make it work "imageObj.crossOrigin = "Anonymous ";" – lavrton Jul 02 '16 at 15:18
  • unfortunately my CDN does not have CORS enabled and is hosted on an external domain.. But I guess I just don't understand why this restriction is in place. I can load images from the CDN via `` tag just fine, so why cant I do the same thing into canvas? – tdc Jul 02 '16 at 15:41
  • I can load it into canvas. But you can not "change" it (read from canvas). It is what filter is doing. – lavrton Jul 03 '16 at 16:36
  • Indeed. So there's no way to override this limitation? I guess I don't understand what this security policy is protecting the end user from. – tdc Jul 05 '16 at 01:36
  • would there be an alternative way to achieve the effect without using filters? Could I overlay something over the image instead of modifying the data? – tdc Jul 05 '16 at 15:24
  • @Prefix The simplest way is to solve CORS restrictions and to try "imageObj.crossOrigin = "Anonymous ";". I do not see any other solutions. – lavrton Jul 06 '16 at 00:24
  • Hi Lavtron - thank you for your help. Do you know a better way to go about what I am trying to accomplish? I am just trying to have an image scaled down and set as fill for a circle shape. Please let me know if you have any ideas of better/easier approaches – tdc Jul 06 '16 at 00:33