【问题标题】:Circle animation random color圆形动画随机颜色
【发布时间】:2015-08-27 20:16:56
【问题描述】:

您好,我尝试创建一个带有圆圈的动画。函数drawRandom(drawFunctions) 应该是三个drawcircle 函数之一,并且应该把它带到画布上。现在的问题是这个函数每秒执行一次(主循环)并且圆圈改变了他的颜色。我该如何解决?

    window.onload = window.onresize = function() {
  var C = 1; // canvas width to viewport width ratio
  var el = document.getElementById("myCanvas");


  var viewportWidth = window.innerWidth;
  var viewportHeight = window.innerHeight;

  var canvasWidth = viewportWidth * C;
  var canvasHeight = viewportHeight;
  el.style.position = "fixed";
  el.setAttribute("width", canvasWidth);
  el.setAttribute("height", canvasHeight);
  var x = canvasWidth / 100;
  var y = canvasHeight / 100;
var ballx = canvasWidth / 100;
var n;


  window.ctx = el.getContext("2d");
  ctx.clearRect(0, 0, canvasWidth, canvasHeight);
  // draw triangles


  function init() {
        ballx;      
        return setInterval(main_loop, 1000);
  }
  function drawcircle1()
  {
  var radius = x * 5;
    ctx.beginPath();
      ctx.arc(ballx * 108, canvasHeight / 2, radius, 0, 2 * Math.PI, false);
      ctx.fillStyle = 'yellow';
      ctx.fill(); 
  }
function drawcircle2()
  {
  var radius = x * 5;
    ctx.beginPath();
      ctx.arc(ballx * 108, canvasHeight / 2, radius, 0, 2 * Math.PI, false);
      ctx.fillStyle = 'blue';
      ctx.fill(); 
  }
  function drawcircle3()
  {
  var radius = x * 5;
    ctx.beginPath();
      ctx.arc(ballx * 105, canvasHeight / 2, radius, 0, 2 * Math.PI, false);
      ctx.fillStyle = 'orange';
      ctx.fill(); 
  }

  function draw() {   
        var counterClockwise = false;

   ctx.clearRect(0, 0, canvasWidth, canvasHeight);

    //first halfarc
   ctx.beginPath();
    ctx.arc(x * 80, y * 80, y * 10, 0 * Math.PI, 1 * Math.PI, counterClockwise);
    ctx.lineWidth = y * 1;
    ctx.strokeStyle = 'black';
    ctx.stroke();





    // draw stop button
    ctx.beginPath();
      ctx.moveTo(x * 87, y * 2);
      ctx.lineTo(x * 87, y * 10);
      ctx.lineWidth = x;
      ctx.stroke();
      ctx.beginPath();
      ctx.moveTo(x * 95, y * 2);
      ctx.lineTo(x * 95, y * 10);
      ctx.lineWidth = x;
      ctx.stroke();


      function drawRandom(drawFunctions){
    //generate a random index
    var randomIndex = Math.floor(Math.random() * drawFunctions.length);

    //call the function
    drawFunctions[randomIndex]();
}
drawRandom([drawcircle1, drawcircle2, drawcircle3]);


  }

  function update() {
    ballx -= 0.1;


    if (ballx < 0) {
      ballx = -radius;         


    }

  }







  function main_loop() {
    draw();
    update();
    collisiondetection();

  }


  init();

            function initi() {
                console.log('init');
                // Get a reference to our touch-sensitive element
                var touchzone = document.getElementById("myCanvas");
                // Add an event handler for the touchstart event
                touchzone.addEventListener("mousedown", touchHandler, false);
            }

            function touchHandler(event) {
                // Get a reference to our coordinates div
                var can = document.getElementById("myCanvas");
                // Write the coordinates of the touch to the div
                if (event.pageX < x * 50 && event.pageY > y * 10) {
                    ballx += 1;
                } else if (event.pageX > x * 50 && event.pageY > y * 10 ) {
                    ballx -= 1;
                }

                console.log(event, x, ballx);

                draw();


            }
            initi();
            draw();
}

【问题讨论】:

    标签: javascript html cordova canvas


    【解决方案1】:

    看看我写的代码:

            var lastTime = 0;
            function requestMyAnimationFrame(callback, time)
            {
                var t = time || 16;
                var currTime = new Date().getTime();
                var timeToCall = Math.max(0, t - (currTime - lastTime));
                var id = window.setTimeout(function(){ callback(currTime + timeToCall); }, timeToCall);
                lastTime = currTime + timeToCall;
                return id;
            }
            var canvas = document.getElementById("canvas");
            var context = canvas.getContext("2d");
            canvas.width = window.innerWidth - 20;
            canvas.height = window.innerHeight - 20;
            canvas.style.width = canvas.width + "px";
            canvas.style.height = canvas.height + "px";
            var circles = [];
            var mouse =
            {
                x: 0,
                y: 0
            }
            function getCoordinates(x, y)
            {
                return "(" + x + ", " + y + ")";
            }
            function getRatio(n, d)
            {
                // prevent division by 0
                if (d === 0 || n === 0)
                {
                    return 0;
                }
                else
                {
                    return n/d;
                }
            }
            function Circle(x,y,d,b,s,c)
            {
                this.x = x;
                this.y = y;
                this.diameter = Math.round(d);
                this.radius = Math.round(d/2);
                this.bounciness = b;
                this.speed = s;
                this.color = c;
                this.deltaX = 0;
                this.deltaY = 0;
                this.drawnPosition = "";
                this.fill = function()
                {
                    context.beginPath();
                    context.arc(this.x+this.radius,this.y+this.radius,this.radius,0,Math.PI*2,false);
                    context.closePath();
                    context.fill();
                }
                this.clear = function()
                {
                    context.fillStyle = "#ffffff";
                    this.fill();
                }
                this.draw = function()
                {
                    if (this.drawnPosition !== getCoordinates(this.x, this.y))
                    {
                        context.fillStyle = this.color;
                        // if commented, the circle will be drawn if it is in the same position
                        //this.drawnPosition = getCoordinates(this.x, this.y);
                        this.fill();
                    }
                }
                this.keepInBounds = function()
                {
                    if (this.x < 0)
                    {
                        this.x = 0;
                        this.deltaX *= -1 * this.bounciness;
                    }
                    else if (this.x + this.diameter > canvas.width)
                    {
                        this.x = canvas.width - this.diameter;
                        this.deltaX *= -1 * this.bounciness;
                    }
                    if (this.y < 0)
                    {
                        this.y = 0;
                        this.deltaY *= -1 * this.bounciness;
                    }
                    else if (this.y+this.diameter > canvas.height)
                    {
                        this.y = canvas.height - this.diameter;
                        this.deltaY *= -1 * this.bounciness;
                    }
                }
                this.followMouse = function()
                {
                    // deltaX/deltaY will currently cause the circles to "orbit" around the cursor forever unless it hits a wall
                    var centerX = Math.round(this.x + this.radius);
                    var centerY = Math.round(this.y + this.radius);
                    if (centerX < mouse.x)
                    {
                        // circle is to the left of the mouse, so move the circle to the right
                        this.deltaX += this.speed;
                    }
                    else if (centerX > mouse.x)
                    {
                        // circle is to the right of the mouse, so move the circle to the left
                        this.deltaX -= this.speed;
                    }
                    else
                    {
                        //this.deltaX = 0;
                    }
                    if (centerY < mouse.y)
                    {
                        // circle is above the mouse, so move the circle downwards
                        this.deltaY += this.speed;
                    }
                    else if (centerY > mouse.y)
                    {
                        // circle is under the mouse, so move the circle upwards
                        this.deltaY -= this.speed;
                    }
                    else
                    {
                        //this.deltaY = 0;
                    }
                    this.x += this.deltaX;
                    this.y += this.deltaY;
                    this.x = Math.round(this.x);
                    this.y = Math.round(this.y);
                }
            }
            function getRandomDecimal(min, max)
            {
                return Math.random() * (max-min) + min;
            }
            function getRoundedNum(min, max)
            {
                return Math.round(getRandomDecimal(min, max));
            }
            function getRandomColor()
            {
                // array of three colors
                var colors = [];
                // go through loop and add three integers between 0 and 255 (min and max color values)
                for (var i = 0; i < 3; i++)
                {
                    colors[i] = getRoundedNum(0, 255);
                }
                // return rgb value (RED, GREEN, BLUE)
                return "rgb(" + colors[0] + "," + colors[1] + ", " + colors[2] + ")";
            }
            function createCircle(i)
            {
                // diameter of circle
                var minDiameter = 25;
                var maxDiameter = 50;
                // bounciness of circle (changes speed if it hits a wall)
                var minBounciness = 0.2;
                var maxBounciness = 0.65;
                // speed of circle (how fast it moves)
                var minSpeed = 0.3;
                var maxSpeed = 0.45;
                // getRoundedNum returns a random integer and getRandomDecimal returns a random decimal
                var x = getRoundedNum(0, canvas.width);
                var y = getRoundedNum(0, canvas.height);
                var d = getRoundedNum(minDiameter, maxDiameter);
                var c = getRandomColor();
                var b = getRandomDecimal(minBounciness, maxBounciness);
                var s = getRandomDecimal(minSpeed, maxSpeed);
                // create the circle with x, y, diameter, bounciness, speed, and color
                circles[i] = new Circle(x,y,d,b,s,c);
            }
            function makeCircles()
            {
                var maxCircles = getRoundedNum(2, 5);
                for (var i = 0; i < maxCircles; i++)
                {
                    createCircle(i);
                }
            }
            function drawCircles()
            {
                var ii = 0;
                for (var i = 0; ii < circles.length; i++)
                {
                    if (circles[i])
                    {
                        circles[i].draw();
                        ii++;
                    }
                }
            }
            function clearCircles()
            {
                var ii = 0;
                for (var i = 0; ii < circles.length; i++)
                {
                    if (circles[i])
                    {
                        circles[i].clear();
                        ii++;
                    }
                }
            }
            function updateCircles()
            {
                var ii = 0;
                for (var i = 0; ii < circles.length; i++)
                {
                    if (circles[i])
                    {
                        circles[i].keepInBounds();
                        circles[i].followMouse();
                        ii++;
                    }
                }
            }
            function update()
            {
                requestMyAnimationFrame(update,10);
                updateCircles();
            }
            function draw()
            {
                requestMyAnimationFrame(draw,1000/60);
                context.clearRect(0,0,canvas.width,canvas.height);
                drawCircles();
            }
            window.addEventListener("load", function()
            {
                window.addEventListener("mousemove", function(e)
                {
                    mouse.x = e.layerX || e.offsetX;
                    mouse.y = e.layerY || e.offsetY;
                });
                makeCircles();
                update();
                draw();
            });
    

    【讨论】:

      猜你喜欢
      • 2012-11-21
      • 1970-01-01
      • 1970-01-01
      • 2014-06-16
      • 1970-01-01
      • 2018-03-21
      • 1970-01-01
      • 1970-01-01
      • 2018-10-05
      相关资源
      最近更新 更多