2016-07-18 4 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/API/CanvasRenderingContext2D/globalCompositeOperation) 또는'getImageData' +'putImageData'가 이것을 달성 할 수 있습니다.)하지만, 당신의 경우 (부분적으로 투명한 스트로크), 당신은 엉망인 결과를 얻습니다 (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); 
관련 문제