你好我正在尝试在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>
答案 0 :(得分: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();