【问题标题】:Set pixels of canvas to transparent again再次将画布的像素设置为透明
【发布时间】:2015-08-19 03:18:38
【问题描述】:

我想画一幅画,擦掉一些部分,然后在上面重新画。大致如下:

ctx.drawImage(favicon, 0, 0);
ctx.fillStyle = 'transparent';
ctx.fillRect(10, 0, 6, 6);
ctx.fillStyle = 'red';
ctx.fillRect(12, 0, 4, 4);

如何删除部分图像?

【问题讨论】:

    标签: javascript canvas


    【解决方案1】:

    .clearRect 是一个不错的选择,如对您问题的赞成评论中所示。

    如果您有非矩形区域(或只是一组像素)要透明,那么您也可以使用destination-out 合成使这些像素透明。

    此示例从 JellyBeans 图像开始,并从中切出太阳图像:

    糖豆

    太阳(用作不规则形状的橡皮擦)

    抹去太阳形状的糖豆

    带注释的示例代码:

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var cw=canvas.width;
    var ch=canvas.height;
    
    
    var jellybeans=new Image();
    jellybeans.onload=start;
    jellybeans.src="https://dl.dropboxusercontent.com/u/139992952/multple/jellybeans.jpg";
    var sun=new Image();
    sun.onload=start;
    sun.src='https://dl.dropboxusercontent.com/u/139992952/multple/sun.png';
    var imageCount=2;
    function start(){
    
      // wait for all images to load
      if(--imageCount>0){return;}
    
      // resize the canvas to jellybean size
      canvas.width=jellybeans.width;
      canvas.height=jellybeans.height;
    
      // draw the jellybeans on the canvas
      ctx.drawImage(jellybeans,0,0);
    
      // Set compositing to "destination-out"
      // All new drawings will act to erase existing pixels
      ctx.globalCompositeOperation='destination-out';
    
      // Draw the sun image
      // Drawing will erase the sun image shape from the jellybeans 
      // You could also erase with any drawing commands (lines,arcs,curves,etc)
      ctx.drawImage(sun,100,50);
    
      // always clean up!
      // Reset compositing to default mode
      ctx.globalCompositeOperation='source-over';
    
    }
    #canvas{border:1px solid red; margin:0 auto; }
    <h4>Jellybeans with sun-shaped erased</h4>
    <canvas id="canvas" width=300 height=300></canvas>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-03
      • 1970-01-01
      • 1970-01-01
      • 2012-03-02
      • 2012-07-21
      • 1970-01-01
      • 1970-01-01
      • 2012-04-18
      相关资源
      最近更新 更多