rog*_*hat 2 javascript html5 canvas css3
我必须用HTML5/CSS3创建一个球类游戏.同样可以看到JSFiddle.
现在我想要的是每次从墙上反弹时改变球的颜色.
var context;
var dx = 4;
var dy = 4;
var y = 150;
var x = 10;
function draw() {
context = myCanvas.getContext('2d');
context.clearRect(0, 0, 300, 300);
context.beginPath();
context.arc(x, y, 20, 0, Math.PI * 2, true);
context.closePath();
context.fill();
if (x < 0 || x > 300)
dx = -dx;
if (y < 0 || y > 300)
dy = -dy;
x += dx;
y += dy;
}
setInterval(draw, 10);Run Code Online (Sandbox Code Playgroud)
#container {
text-align: center;
}
#myCanvas {
background: #fff;
border: 1px solid #cbcbcb;
text-align: center;
}Run Code Online (Sandbox Code Playgroud)
<div id="container">
<div>
<canvas id="myCanvas" width="300" height="300"></canvas>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
我不知道怎么做.css3可以用来做这个吗?
随机颜色功能来自这里:https://stackoverflow.com/a/1484514/2042240
这将使其在每次反弹时都发生变化.
https://jsfiddle.net/e0b1gkc4/4/
var context;
var dx= 4;
var dy=4;
var y=150;
var x=10;
function draw(){
context= myCanvas.getContext('2d');
context.clearRect(0,0,300,300);
context.beginPath();
context.arc(x,y,20,0,Math.PI*2,true);
context.closePath();
context.fill();
if( x<0 || x>300){
dx=-dx;
context.fillStyle = getRandomColor();
}
if( y<0 || y>300){
dy=-dy;
context.fillStyle = getRandomColor();
}
x+=dx;
y+=dy;
}
setInterval(draw,10);
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
Run Code Online (Sandbox Code Playgroud)