HTML5 Canvas globalCompositeOperation同时打火机和source-atop

时间:2015-04-13 01:53:29

标签: javascript html5 canvas

有没有办法使用globalCompositeOperation" light"并同时使用source-atop? (Aka打火机,但只有已经画出的东西。)

1 个答案:

答案 0 :(得分:2)

您一次只能设置一个合成操作。

解决方法:您可以使用第二个画布来执行“lightenAtop”:

  1. 创建第二个内存中的画布。
  2. 将主画布内容绘制到内存中的画布上。
  3. 在内存中画布上将合成设置为lighten
  4. 将覆盖的颜色/图像绘制到内存中的画布上
  5. 在主画布上将合成设置为“source-in”。
  6. 将内存中的画布绘制到主画布上。
  7. 结果:减轻和减轻的组合source-atop compositing!
  8. 左:原始红色矩形,中间:蓝色填充,右: lightenAtop

    enter image description here enter image description here enter image description here

    示例代码和演示:

    此示例仅使用实心填充点亮,但您也可以drawImage代替fillRect

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var cw=canvas.width;
    var ch=canvas.height;
    
    ctx.fillStyle='rgba(250,0,0,255)';
    ctx.fillRect(50,50,100,75);
    
    lightenAtop('rgba(0,0,255,255)');
    
    function lightenAtop(rgba){
      var compositor=document.createElement('canvas');
      var cctx=compositor.getContext('2d');
      compositor.width=canvas.width;
      compositor.height=canvas.height;
      cctx.drawImage(canvas,0,0);
      cctx.globalCompositeOperation='lighter';
      cctx.fillStyle=rgba;
      cctx.fillRect(0,0,cw,ch);
      ctx.globalCompositeOperation='source-in';
      ctx.drawImage(compositor,0,0);
      ctx.globalCompositeOperation='source-over';
    }
    body{ background-color:white; }
    #canvas{border:1px solid red;}
    <h4>Original red rect "lightened" with blue rect</h4>
    <canvas id="canvas" width=300 height=300></canvas>