0

您好,我正在尝试在 JavaScript 上创建一个球,该球在球经过时具有带有渐变的背景,到目前为止,当我尝试用以下内容填充背景时,我的球弹跳代码似乎有效:

 context.fillStyle = "rgba(0,0,0,0.10)"; //this is what i am trying to do as the                 gradient
      context.fillRect(0,0, canvas.width, canvas.height);

是当我把所有事情都搞砸的时候,我不确定我做错了什么,任何帮助都非常感谢,下面是我对弹跳球采取的方法:

 <script>
     var context;
     var posX=100;
     var posY=200;
      var dx=5;
      var dy=5;



    function bouncyBall()
    {
    var canvas = document.getElementById("circleCanvas");
    context= canvas.getContext('2d');
     setInterval(draw,10);



      }

      function draw()
     {


    context.clearRect(0,0, 800,600);
    context.beginPath();
    context.fillStyle="orange";



    //to draw the circle
    context.arc(posX,posY,20,0,Math.PI*2,true);
    context.closePath();
    context.fill();


    // this will do the boundares
   if( posX<0 || posX>800) dx=-dx; 
    if( posY<0 || posY>600) dy=-dy; 
   posX = posX+dx; 
   posY = posY+dy;


   }


      </script>
   <body  onload= "bouncyBall();" >
    <h1>A Ball Bouncing!</h1>
     <canvas id = "circleCanvas" width="800" height="600">


     </canvas>
       <ul>

        </ul>
           </body>
</html>
4

1 回答 1

1

以下是创建用于球画布的线性渐变的方法:

// think of createLinearGradient as a line
// the gradient will follow that line

var orangeGradient = context.createLinearGradient(
                         canvas.width/2, 0, canvas.width/2, canvas.height);

// then define where each color will be along the line 
// (0.00==start of line,1.00==end of line)

orangeGradient.addColorStop(0, '#ffdd00');   
orangeGradient.addColorStop(1, '#cc6600');

// and finally set the fillStyle to your new gradient

context.fillStyle = orangeGradient;
context.fill();
于 2013-10-24T14:25:24.283 回答