Ad

How To Apply ColorMatrix Along With Canvas Context

I am working on canvas and using EaselJS library to play along. With EaselJS, I am able to apply the ColorMatrix using Filters

    const myGraphics = new createjs.Shape();
    myGraphics.graphics.bf(img, 'no-repeat')
        .drawCircle(x, y, cursorSize);

    const colorMatrix = [0.3, 0.3, 0.3, 0, 0, 0.3, 0.3, 0.3, 0, 0, 0.3, 0.3, 0.3, 0, 0, 0, 0, 0, 1, 0];
    const blurFilter = new createjs.BlurFilter(5, 5, 1);
    myGraphics.filters = [new createjs.ColorMatrixFilter(colorMatrix), blurFilter];

    myGraphics.cache(0, 0, 500, 500);

Can the same be applied without using EaselJS ? I have the below code

    const patt = ctx.createPattern(img, 'no-repeat');
    ctx.filter = 'blur(5px)';
    ctx.fillStyle = patt;
    ctx.beginPath();
    ctx.arc(x, y, r1, 0, Math.PI * 2);
    ctx.fill();

How can I apply the colorMatrix filter to the above canvas context?

Thanks in advance

Ad

Answer

You can use svg filters with the css url(#filter_id) notation for the context.filter property, and for a color-matrix, use the <feColorMatrix> svg element :

const canvas = document.getElementById( 'canvas' );
const  ctx = canvas.getContext( '2d' );
const img = new Image();
img.onload = e => {
  ctx.fillStyle = ctx.createPattern(img, 'repeat');
  ctx.filter = 'url(#matrix)';
  ctx.rect( 20, 20, 460, 460 );
  ctx.scale( 0.15, 0.15 );
  ctx.fill();
};
img.src = "https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png";
<svg width="0" height="0" style="position:absolute;z-index:-1">
  <filter id="matrix">
    <feColorMatrix type="matrix" values="0.3, 0.3, 0.3, 0, 0, 0.3, 0.3, 0.3, 0, 0, 0.3, 0.3, 0.3, 0, 0, 0, 0, 0, 1, 0"/>
  </filter>
</svg>
<canvas id="canvas"> width="500" height="500"></canvas>

Ad
source: stackoverflow.com
Ad