簡體   English   中英

使用HTML5畫布掩蓋putImageData?

[英]Mask for putImageData with HTML5 canvas?

我想從現有圖像中獲取不規則形狀的部分,並使用HTML5畫布將其渲染為Javascript中的新圖像。 因此,只會復制多邊形邊界內的數據。 我提出的方法涉及:

  1. 在新畫布中繪制多邊形。
  2. 使用clip創建蒙版
  3. 使用getImageData (矩形)從原始畫布復制數據
  4. 使用putImageData將數據應用於新畫布

它不起作用,整個矩形(例如來自邊界外的源的東西)仍然出現。 這個問題解釋了原因:“規范說putImageData不會受到裁剪區域的影響。” 黨!

我也嘗試繪制形狀,設置context.globalCompositeOperation = "source-in" ,然后使用putImageData 相同的結果:沒有應用蒙版。 我懷疑是因為類似的原因。

關於如何實現這一目標的任何建議? 這是我正在進行的工作的基本代碼,以防我不知道自己要做什么。 (不要太努力地調試它,它會從使用很多不在這里的函數的代碼中清理/提取,只是試圖顯示邏輯)。

 // coords is the polygon data for the area I want
   context = $('canvas')[0].getContext("2d");
   context.save();
   context.beginPath();
   context.moveTo(coords[0], coords[1]);
   for (i = 2; i < coords.length; i += 2) {
     context.lineTo(coords[i], coords[i + 1]);
   }
   //context.closePath();
   context.clip();

   $img = $('#main_image');
   copy_canvas = new_canvas($img); // just creates a new canvas matching dimensions of image
   copy_ctx = copy.getContext("2d");

   tempImage = new Image();
   tempImage.src = $img.attr("src");
   copy_ctx.drawImage(tempImage,0,0,tempImage.width,tempImage.height);

  // returns array x,y,x,y with t/l and b/r corners for a polygon
  corners = get_corners(coords)
  var data = copy_ctx.getImageData(corners[0],corners[1],corners[2],corners[3]);
  //context.globalCompositeOperation = "source-in";
  context.putImageData(data,0,0);
  context.restore();

不要使用putImageData

只需在內存畫布中使用document.createElement創建一個額外的掩碼,並將其應用於drawImage()globalCompositeOperation函數(取決於您選擇正確模式所需的順序;

在這里類似代碼在這里 (介意CasparKleijne.Canvas.GFX.Composite函數)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM