2016-02-24 59 views
1

我有一張地圖的帆布。我希望畫布變暗,然後畫布中的多邊形變得透明(聚焦,不會變暗)。帆布上的透明多邊形

我無法獲得多邊形的透明度。現在我用一種顏色填充多邊形,但如何用透明顏色填充多邊形?

我做錯了嗎?

canv = document.getElementById("canvas"); 
    ctx = canv.getContext("2d"); 
    image = document.getElementById('img_holder'); 
    ctx.drawImage(image,0,0, canv.width, canv.height); 

ctx.fillStyle = "rgba(0, 0, 0, 0.5)"; 
      ctx.fillRect(0, 0, 870, 500); 
      ctx.restore(); 

ctx.save(); 
ctx.globalCompositeOperation = 'destination-out'; 
ctx.beginPath(); 
ctx.moveTo(10, 10); 
ctx.lineTo(100,50); 
ctx.lineTo(100, 100); 
ctx.lineTo(200, 150); 
ctx.lineTo(10, 150); 
ctx.fillStyle = "rgba(0, 0, 0, 0.5)"; 
ctx.closePath(); 
ctx.fill(); 

Link to my fiddle

+1

爲什麼使用'ctx.globalCompositeOperation'繪製透明形狀?你簡單的'fillStyle = rgba'應該可以做到這一點......如果你需要繪製一個透明的圖像,'globalCompositeOperation'是有用的,但是填充一個形狀很容易,就像'fillStyle'一樣... – somethinghere

+0

@somethinghere - 我很喜歡新的畫布,所以也許我誤解了你的答案 - 但這是你的意思嗎? http://jsfiddle.net/Sykvr/142/。這劑量使多邊形完全透明。我希望它能像真正的照片一樣成爲父母,而不需要黑色調光器覆蓋。也許我誤解了它的工作原理。 –

+0

您是否試圖從黑色透明覆蓋層中刪除多邊形? – somethinghere

回答

1

要從透明覆蓋切出的圖像,你可以去兩種方式:

  • 從矩形切出多邊形繪圖
  • 繪製圖像到前多邊形

隨着您目前的設置,後者是更容易實現使用clip

var canvas = document.getElementById("canvas"); 
 
var ctx  = canvas.getContext("2d"); 
 
var image = new Image; 
 

 
image.addEventListener('load', function(){ 
 
    
 
    ctx.drawImage(image, 0, 0, canvas.width, canvas.height); 
 

 
    ctx.fillStyle = "rgba(0, 0, 0, 0.5)"; 
 
    ctx.fillRect(0, 0, 870, 500); 
 
    
 
    // Use save and restore to make sure the canvas restores its non-clipping path setup after clipping 
 
    ctx.save(); 
 
    ctx.beginPath(); 
 
    ctx.moveTo(10, 10); 
 
    ctx.lineTo(100,50); 
 
    ctx.lineTo(100, 100); 
 
    ctx.lineTo(200, 150); 
 
    ctx.lineTo(10, 150); 
 
    ctx.closePath(); 
 
    // Use the path just created as a clipping path 
 
    ctx.clip(); 
 
    // Draw anywhere in the image, only inside the clipping path will be drawn 
 
    ctx.drawImage(image,0,0, canvas.width, canvas.height); 
 
    // restore so you can draw outside the clipping path again 
 
    ctx.restore(); 
 
    
 
}); 
 

 
image.src = 'http://www.marinadivenezia.it/media/467/w-876/h-506/00-MAPPA-2015-GENERICA.jpeg';
<canvas id="canvas" width="400" height="300"></canvas>

我也建議你使用明確的名稱爲您的變量 - 有幾乎沒有任何advntage縮短畫布canv,但它使赫克更清晰。另外,請確保你var關鍵字聲明瞭你的變量 - 這是很常見的做法,它與聲明它們稍有不同,可能是錯誤的。

+0

非常感謝!我也創建了這個解決方案 - http://jsfiddle.net/eGjak/2736/,但我不知道它是否是正確的方法,但它似乎工作:-)但我會用你的,非常感謝: - ) –

+0

@AndreasBaran是我還是那張貼的小提琴只是覆蓋整個透明黑色?這似乎並不奏效。這種方法可以工作,但是你需要將圖像的所有四個角連接到切口,以確保形狀實際上是矩形減去你的多邊形,然後填充它......但是這聽起來比'clip'更復雜, :) – somethinghere

+1

你說得對 - 我會堅持你的解決方案。再次感謝:-) –