gpt4 book ai didi

javascript - 再次将 Canvas 像素设置为透明

转载 作者:行者123 更新时间:2023-11-28 15:19:40 26 4
gpt4 key购买 nike

我想绘制一个图像,删除一些部分,然后在上面再次绘制。大致如下:

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

如何删除图像的部分内容?

最佳答案

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

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

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

软糖

enter image description here

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

enter image description here

太阳形状被删除的软糖

enter image description here

带注释的示例代码:

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>

关于javascript - 再次将 Canvas 像素设置为透明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32075706/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com