我需要一些关于此代码的帮助。有一个蓝色方块(它应该是),但它的路径也是蓝色的!
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,但那没用。也许我错了。请给我一些帮助?还请包括来源/示例。
答案 0 :(得分:1)
使用合成制作新图纸“擦除”现有像素。
“删除”的合成模式为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>