Flickering images in canvas animation

前端 未结 2 1094
说谎
说谎 2021-01-22 07:01
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oR         


        
2条回答
  •  没有蜡笔的小新
    2021-01-22 08:04

    The problem is that a new instance of the image is being reloaded each time they are rendered in the circle. The network delay causes this flashing that you see. By loading the image first and then reusing the data I have removed the flashing.

    Here is a working version: http://codepen.io/anon/pen/JRVJRJ

    I have moved the loading of base_image out side of the make_base function and made it a global variable for reuse in the make_base function. The causes the image to be loaded once and reapplied multiple times.

    window.requestAnimFrame = (function(callback) {
            return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
            function(callback) {
              window.setTimeout(callback, 1000 / 60);
            };
          })(); 
    
    $(function() {
      var centerX = 400,
        centerY = 400,
        radius = 300;
    
      function make_base(ctx, angle) {
          ctx.save();
          var x = centerX + Math.sin(angle) * radius;
          var y = centerY + Math.cos(angle) * radius;
          ctx.translate(x, y);
          ctx.drawImage(base_image, 0, 0);
          ctx.rotate(angle);
          ctx.restore();
      }
    
      function draw(step) {
        var ctx = document.getElementById("canvas").getContext("2d");
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        var angle;
        for (var i = 0; i < 180; i += 10) {
          angle = step + (i * Math.PI / 90);
          make_base(ctx, angle);
        }
      }
    
    base_image = new Image();
        base_image.src = 'https://gxzzxb.files.wordpress.com/2014/12/16mario.png';
        base_image.onload = function(){
          var step = 0;
        draw(step);
    
        setInterval(function() {
      draw(step);
              ++step;
            }, 20);
      }
      });
    

提交回复
热议问题