gpt4 book ai didi

javascript - 使 Canvas 对象的绘制路径透明?

转载 作者:行者123 更新时间:2023-12-03 11:40:12 25 4
gpt4 key购买 nike

我需要一些有关此代码的帮助。有一个蓝色方 block (应该是),但它的路径也是蓝色的!

body{
overflow-y:hidden;
overflow-x:hidden;
}
canvas{
background:url("https://img0.etsystatic.com/038/0/6965312/il_340x270.545626074_sflg.jpg");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onkeydown="move(event.keyCode)">
<script>
var X = 80;
var Y = 20;
function move(keyCode){
myCanvas.fillStyle = "transperant";
myCanvas.fillRect(X, Y, 50, 50);
if(keyCode == 39){
X += 5;
}
if(keyCode == 37){
X -= 5;
}
if(keyCode == 40){
Y += 5;
}
if(keyCode == 38){
Y -= 5;
}
myCanvas.fillStyle = "blue";
myCanvas.fillRect(X, Y, 50,50);
}
</script>
<canvas id="C1" width="900px" height="900px">Uhh, what?!?!</canvas>
<script>
myElement = document.getElementById("C1");
myCanvas = myElement.getContext("2d");
myCanvas.fillStyle = "transperant";
myCanvas.fillRect(80, 20, 50, 50);
</script>
</body>

如何使路径透明/清晰?我尝试了 fillPath,但没有成功。也许我用错了。请给我一些帮助吗?另请附上来源/示例。

最佳答案

使用合成使新绘图“删除”现有像素。

“删除”的合成模式是destination-out

示例代码:

// set compositing to use any new drawings 
// to "erase" existing drawings
ctx.globalCompositeOperation='destination-out';

// draw something
// the canvas will become transparent inside that drawing
ctx.fillRect(100,100,100,100);

// reset compositing to default
ctx.globalCompositeOperation='source-over';

示例代码和演示:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var img=new Image();
img.onload=start;
img.src="https://img0.etsystatic.com/038/0/6965312/il_340x270.545626074_sflg.jpg";
function start(){

canvas.width=img.width;
canvas.height=img.height;
ctx.drawImage(img,0,0);

// set compositing to use any new drawings
// to "erase" existing drawings
ctx.globalCompositeOperation='destination-out';

// draw something
// the canvas will become transparent inside that drawing
ctx.fillRect(100,100,100,100);

// reset compositing to default
ctx.globalCompositeOperation='source-over';

}
body{ background-color: purple; }
canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>

关于javascript - 使 Canvas 对象的绘制路径透明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26317210/

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