2014-10-11 22 views
0


我需要一些帮助这个代码。有一个蓝色方块(应该是),但它的路径也是蓝色的!使画布对象的绘制路径transperant?

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>

你怎样的路径transperant /清楚了吗?我尝试了fillPath,但没有奏效。也许我错了。请给我一些帮助?还请包括来源/例子。

感谢您的时间和先进的升值!

回答

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>

+0

我不知道为什么,但那不是w ork对我来说。帮助使用你的代码? – 2014-10-12 02:31:25

+1

我已经给我的答案添加了示例代码,但没有太多解释:'globalCompositeOperation ='destination-out''会导致未来的图纸擦除当前图纸。祝你的项目好运! – markE 2014-10-12 03:20:30