【问题标题】:CSS3: change the color of the ball every time it bounces off the canvas wallCSS3:每次从画布墙上反弹时改变球的颜色
【发布时间】:2015-10-01 16:05:22
【问题描述】:

我必须用 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);
#container {
  text-align: center;
}
#myCanvas {
  background: #fff;
  border: 1px solid #cbcbcb;
  text-align: center;
}
<div id="container">
  <div>
    <canvas id="myCanvas" width="300" height="300"></canvas>
  </div>
</div>

我不知道该怎么做。 css3可以用来做这个吗?

【问题讨论】:

  • 你不能用 CSS 做到这一点。您必须更改 JS 中的填充颜色(如 context.fillStyle='red'),因为球是 Canvas 绘图。
  • 怎么做?我的意思是每次填充都会生成随机颜色。

标签: javascript html css canvas


【解决方案1】:

随机颜色功能来自这里: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;
}

【讨论】:

  • 你能说得清楚一点吗?我在这里尝试过,似乎运行良好:jsfiddle.net/e0b1gkc4/4
  • 我想我错了,但这很有趣 ;-) 要去调查。
  • @Amit 好的,如果真的有问题,请告诉我;)
  • @nowhere - 经过验证,您的解决方案是可靠的。我担心(假设真的)是调用getContext() 每次都会返回一个新对象,并且这个新对象不会保持以前的样式。我found out 是它必须返回相同的对象,因此将保持样式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-31
  • 1970-01-01
  • 2013-11-30
  • 2021-03-06
  • 2021-11-27
相关资源
最近更新 更多