重复时改变颜色和移动元素的Jquery坐标

Changing color when repeat and Jquery coordinates of moving element

本文关键字:元素 Jquery 坐标 移动 改变 变颜色      更新时间:2023-09-26

我想重新创建一些我看过的JQuery教程,但我现在卡住了。

我正在创建一个对象,它从一个位置开始,在另一个位置结束。图形改变了,但是当它重复的时候,我想让物体改变颜色。我试过创建一个数组,并使用Math.floor(Math.random()元素来做到这一点,但它不起作用。

此外,我尝试使用jQuery做以下事情,即,当我点击图形时,它会给我它在x和y上的位置。

我想做的事情在下面的例子中。

Youtube例子

我的代码到目前为止

<!DOCTYPE html>
<html>
<head>
  <title>Example</title>
  <meta charset="utf-8">
</head>
<body>
    <canvas id="canvas" width="400" height="400"></canvas>
    <script src="https://code.jquery.com/jquery-2.1.0.js"></script>
    <script>
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    var posicion = 0;    
    var tamano = 0;
    setInterval(function () {
    ctx.clearRect(0, 0, 400, 400);
    ctx.fillRect(posicion, 0, tamano, 400-tamano);
    posicion++;
    tamano++;
    if (posicion > 400){
    posicion = 0;
    tamano = 0;
    }
    }, 30);    
    var color = ['red', 'green', 'blue', 'orange', 'yellow'];     
    ctx.fillStyle = color[Math.floor(Math.random() * color.length)];
</script>
</body>
</html>

有没有人可以帮助我或说我做错了什么?

试试这个:

 <script>
    var color = ['red', 'green', 'blue', 'orange', 'yellow'];     
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    var posicion = 0;    
    var tamano = 0;
    setInterval(function () {
    ctx.clearRect(0, 0, 400, 400);
    ctx.fillRect(posicion, 0, tamano, 400-tamano);
    posicion++;
    tamano++;
    if (posicion > 400){
    posicion = 0;
    tamano = 0;
          ctx.fillStyle = color[Math.floor(Math.random() * color.length)];
    }
    }, 30);    
</script>

你必须改变if语句中的颜色。

我刚刚在if语句中添加了ctx.fillStyle = color[Math.floor(Math.random() * color.length)];。在此条件之后,对象将重新启动动画并更改颜色。我还把你的颜色数组上移了。

这里是一个例子,fiddle: https://jsfiddle.net/eugensunic/ocohmgm6/

你可以使用一个函数返回一个随机的颜色,像这样:

function getRandomColor() {
    var letters = '0123456789ABCDEF'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++ ) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}