【问题标题】:How to apply ColorMatrix along with Canvas Context如何将 ColorMatrix 与 Canvas Context 一起应用
【发布时间】:2020-04-15 10:15:30
【问题描述】:

我正在画布上工作并使用 EaselJS 库来玩。 使用 EaselJS,我可以使用滤镜应用 ColorMatrix

    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);

不使用 EaselJS 也可以应用同样的方法吗? 我有以下代码

    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();

如何将 colorMatrix 过滤器应用于上述画布上下文?

提前致谢

【问题讨论】:

    标签: javascript html canvas html5-canvas createjs


    【解决方案1】:

    对于context.filter 属性,您可以使用带有css url(#filter_id) 表示法的svg 过滤器,对于颜色矩阵,使用<feColorMatrix> svg 元素:

    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>

    【讨论】:

      猜你喜欢
      • 2021-07-09
      • 1970-01-01
      • 2019-06-30
      • 2021-10-28
      • 1970-01-01
      • 2019-01-02
      • 1970-01-01
      • 2015-08-30
      • 1970-01-01
      相关资源
      最近更新 更多