2011-08-11 3 views
6

HTML5 캔버스 요소를 사용하여 아래 그림과 같은 그래디언트 효과로 사각형을 그릴 수 있습니까?HTML5 캔버스 요소가있는 사각형 그라디언트

sample

편집 : 모든 의견을 주셔서 감사합니다. 예, 이미 여러 가지 방법을 시도했습니다. 예를 들어 @Loktar에서 제시 한대로 createRadialGradient 메서드를 사용할 수 있습니까? 여기에 몇 가지 예제 코드입니다 :

<html> 
    <head> 
    <title>test</title> 
     <script type="application/x-javascript"> 
     function draw() { 
      var canvas = document.getElementById("canvas"), 
      ctx = canvas.getContext("2d"); 

      var grad1 = ctx.createRadialGradient(50, 50, 0, 50, 50, 50); 
      grad1.addColorStop(0, 'rgba(255, 252, 0, 1)'); 
      grad1.addColorStop(1, 'rgba(68, 205, 37, 1)'); 

      ctx.fillStyle = grad1; 
      ctx.fillRect(0, 0, 100, 100); 
     } 
    </script> 
    </head> 
    <body onload="draw();"> 
    <div> 
     <canvas id="canvas" width="100" height="100"></canvas> 
    </div> 
    </body> 
</html> 

하지만 결과는 내가 원하는 것을 확실히되지 않습니다 :이 GDI +에서 제공 PathGradientBrush 같은 방법으로 쉽게 할 수 있어야

result

. HTML5 캔버스 요소를 사용하여 가능한지 확실하지 않습니다.

+2

지금까지 해보신 것은 무엇입니까? 추신. https://developer.mozilla.org/en/Canvas_tutorial%3aApplying_styles_and_colors 5 분 그리고 그것을 할 수있을거야! – stecb

+1

heh idk 약 5 분. Heres는 나의 무서운 시도, 대답으로 그것을 배치하지 않을 것이다 http://jsfiddle.net/loktar/MAjPQ/1/ – Loktar

+0

obv '5 mins'는 그 문서를 읽고 쉽게 해결책을 얻으려고 노력하는 것을 의미한다. – stecb

답변

4

선형 그래디언트와 클리핑을 조합하여 사용할 수 있습니다. Demo. 코드 :

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

var outerColor = 'rgba(68,205,37,1)'; 
var innerColor = 'rgba(255,252,0,1)'; 

var w = 200; 
var h = 50; 
canvas.width = w; 
canvas.height = h; 

function gradient(dir) { 
    var grad = ctx.createLinearGradient(dir[0], dir[1], dir[2], dir[3]); 

    grad.addColorStop(0, outerColor); 
    grad.addColorStop(0.5, innerColor); 
    grad.addColorStop(1.0, outerColor); 

    return grad; 
} 

// idea: render background gradient and a clipped "bow" 
function background() { 
    ctx.fillStyle = gradient([0, 0, 0, h]); 
    ctx.fillRect(0, 0, w, h); 
} 

function bow() { 
    ctx.save(); 

    ctx.beginPath(); 
    ctx.moveTo(0, 0); 
    ctx.lineTo(w, h); 
    ctx.lineTo(w, 0); 
    ctx.lineTo(0, h); 
    ctx.clip(); 

    ctx.fillStyle = gradient([0, 0, w, 0]); 
    ctx.fillRect(0, 0, w, h); 

    ctx.restore(); 
} 

background(); 
bow(); 
+0

매우 감사합니다 !!! – dreamsfrag