2014-10-11 50 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