简体   繁体   中英

Bouncing Ball On JavaScript with background and a Gradient

Hello I'm trying to create a ball on JavaScript that possess a background with a Gradient as the ball passes by, by far my code for the ball bouncing seems to work, when I try to fill the background with:

 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);

is when I mess everything up I'm not sure what am i doing wrong any help is kindly apprecciated, the one below is the approach I have taken for the bouncing ball :

 <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>

Here's how you create a linear gradient for use on your ball-canvas:

// 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM