在画布上绘制光线

时间:2012-12-06 15:44:08

标签: html5 html5-canvas gradient

有人帮我画这样的光线:

Example image

我已经尝试了很多次但是没能。无需完美匹配颜色,至少是基本线和渐变。

1 个答案:

答案 0 :(得分:5)

http://jsbin.com/uhuwud/1/edit

(function(){
    var can = document.getElementById("lightray"),
        ctx = can.getContext('2d'),
        wid = can.width,
        hei = can.height,
        ang = -90 * Math.PI/180,
        spn = 80 * Math.PI/180,
        ctr = {x: 200, y:200},
        rad = 200,
        grd = ctx.createRadialGradient(ctr.x, ctr.y, 0, ctr.x, ctr.y, rad);

    grd.addColorStop(0, 'rgba(0,200,255,.25)');
    grd.addColorStop(0.75, 'rgba(0,0,0,0.25)');
    grd.addColorStop(1, 'rgba(0,0,0,0)');
    ctx.fillStyle = grd;



  (function draw(){
    ctx.clearRect(0,0,wid,hei);
    ang = Math.sin(new Date()/1000) * Math.PI/2;
    spn = (Math.abs(Math.sin(new Date()/1000/3)) * 120 + 30) * Math.PI/180;

// The below code is the pertinent part
// the concept is that I'm drawing a radial gradient in an arc, and decreasing the span
// of the arc some number of times. This will create the side-to-side fading. 
    for (var i = 2; i < 10; i+=0.1){
      ctx.beginPath();
      ctx.moveTo(ctr.x,ctr.y);
      ctx.arc(ctr.x, ctr.y, rad, ang - spn/i, ang + spn/i, false);
      ctx.closePath();
      ctx.fill();
    }
// the above code

    webkitRequestAnimationFrame(draw);
  })();
})();