2016-07-18 5 views
1

パスのfillStyleを完全に透明に変更しようとしていますが、代わりにブレンドされた色が表示されます。キャンバス上のパスのfillStyleを変更すると、実際には変更がブレンドされません。

/***************************** 
ALL BELOW JUST SIMULATING CASE 
*****************************/ 
var c1 = document.getElementById("cool"); 
var ctx = c1.getContext("2d") 

var elem=[0,0,50,0,100,0]; 
var elem2=[50,0,50,50,50,100]; 

var i=1; 

var path = new Path2D(); 
path.moveTo(elem[i+1], elem[i+2]); 
path.lineTo(elem2[i+1], elem2[i+2]); 
path.lineTo(elem2[i-1], elem2[i]); 
path.lineTo(elem[i+1], elem[i+2]); 
path.closePath(); 

ctx.fillStyle = getRndColor(); 
ctx.strokeStyle = ctx.fillStyle; 
ctx.fill(path); 
ctx.stroke(path); 

//this function shouldn't have impact on problem, but i put it here just in case 
var getRndColor = function() { 
    var r = 255*Math.random()|0, 
     g = 255*Math.random()|0, 
     b = 255*Math.random()|0; 
    return 'rgb(' + r + ',' + g + ',' + b + ')'; 
} 

/***************************** 
ALL ABOVE JUST SIMULATING CASE 
*****************************/ 

var changeElement = function(path) { 
    ctx.fillStyle = "rgba(0,0,0,0)"; 
    ctx.strokeStyle = ctx.fillStyle; 
    ctx.fill(path); 
    ctx.stroke(path); 
    console.log(ctx.fillStyle); 
} 

changeElement(path); //if you try e.g. 50% opacity, you will see that color blends 

パスfillStyleを変更するにはどうすればよいですか?キャンバスの長方形ではない領域をクリアすることは可能ですか?

+1

あなたのコンテキストの非矩形領域([ 'globlaCompositeOperation'](https://developer.mozilla.org/en-US/docs/Webをクリアする方法がありますあなたが(部分的に透明なストローク)では、あなたは醜い結果しか得られません(gCOは動作しません、そして、あなたはアンチエイリアスを取得します) 'putImageData'メソッドを使ってエイリアスを作ります)。したがって、実際の使用状況に応じて、すべてを再描画するか、またはパスを描画する前にバッファキャンバスにコンテキストのコピーを保持し、 'drawImage'を使用してこの状態を元に戻します。 – Kaiido

+0

私は私の概念を再構築しなければならないと思います。私は再描画を試みるつもりでしたが、このアイデアのおかげで追加のキャンバスの使用は考慮しませんでした:) – jazzgot

+0

man、globalCompositeOperationは完全に問題を解決しました。私はあなたを尊敬することができ、将来の誰かが同じ問題を抱えている場合、彼はここで解決策を見つけることができます。 – jazzgot

答えて

1

Okey、ここでは簡単な解決方法があります。 Kalidoに大きなおかげです。

私の場合、ちょうどglobalCompositeOperationの値をsource-inに変更すると、色を混ぜる代わりに色と不透明度を変更できます。

この値を全体のコンテキストに変更すると、使用後にデフォルト値に戻すことができます。

私のコード例:

var changeElement = function(path) { 
    ctx.globalCompositeOperation = "source-in"; 
    ctx.fillStyle = "rgba(0,0,0,0)"; 
    ctx.strokeStyle = ctx.fillStyle; 
    ctx.fill(path); 
    ctx.stroke(path); 
    ctx.globalCompositeOperation = "source-over"; //setting back to default value to prevent odd behavior of other part of canvas. 
} 

changeElement(path); 
関連する問題