在画布

时间:2016-06-05 14:23:16

标签: javascript canvas html5-canvas

我尝试用canvas元素中的图像编写循环脚本。我尝试做什么:

  1. 我想在json文件中加载所有图像数据,例如url标题和名称,然后首先在jj文件中加载window.onload}
  2. 当图像数据加载时我想显示加载gif图像,之后我想在canvas元素中显示加载的json文件中的第一张图像
  3. 当我点击名为“点击匹配”的按钮时,这是一个主要问题我想运行的功能每个都会在画布元素中用动画画出随机图像 - 简单的动画(我的意思是老虎机)。
  4. 我有ajax请求,随机数函数,动画等简单类。

    逻辑是简单的点击按钮 - >显示几个图像 - >在随机图像上停止 - >检查所选类型的图片标题 - >结束(再次点击按钮时再次重复)

    我不知道如何将我的功能放在一个脚本中。

    我的json文件

    [
          {
            "url": "http://lorempixel.com/400/200/",
            "filename": "example-1",
            "caption": "car"
          },
          {
            "url": "http://lorempixel.com/400/200/",
            "filename": "example-2",
            "caption": "bike"
          },
          {
            "url": "http://lorempixel.com/400/200/",
            "filename": "example-3",
            "caption": "quad"
          },
          {
            "url": "http://lorempixel.com/400/200/",
            "filename": "example-4",
            "caption": "truck"
          },
          {
            "url": "http://lorempixel.com/400/200/",
            "filename": "example-5",
            "caption": "pickup"
          },
          {
            "url": "http://lorempixel.com/400/200/",
            "filename": "example-6",
            "caption": "pogo"
          }
    ]
    

    包含JavaScript文件的HTML

    // ajax request
    function createXHR() {
      if(typeof XMLHttpRequest != "undefined") {
        return new XMLHttpRequest();
      } else if(typeof ActiveXObject != "undefined") {
        if(typeof arguments.callee.activeXString != "string") {
          var versions = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp"],
              i, len;
          for(i=0, len=versions.length; i<len; i++) {
            try {
              new ActiveXObject(versions[i]);
              arguments.callee.activeXString = versions[i];
              break;
            } catch (ex) {
              // skip
            }
          }
        }
    
        return new ActiveXObject(arguments.callee.activeXString);
      } else {
        throw new Error("No XHR object available.");
      }
    }
    
    var jsonUrl = "myJSON.json";
    var xhr = createXHR();
    xhr.onreadystatechange = function() {
      if(xhr.readyState == 4) {
        if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
          alert(xhr.responseText);
          // json file
          //var jsonArr = JSON.parse(xhr.responseText);
        } else {
          alert("Request was unsuccessful: " + xhr.status);
        }
      }
    };
    xhr.open("get", jsonUrl, true);
    xhr.send(null);
    // how to "show first image in canwas" when all images will be loaded and in meanwhile show loading image?
    /*
    window.onload = function() {
      setTimeout(function() {
        // preload image
        new Image().src = "loading.gif"
      }, 1000);
    };
    */
    
    
    // show first image inside canvas
    window.onload = function() {
      var canvas = document.getElementById("myCanvas");
      var context = canvas.getContext("2d");
      var imageObj = new Image();
      imageObj.onload = function() {
        var destX = 0;
        var destY = 0;
        context.drawImage(this, destX, destY);
      };
      // here should be firs image in json file
      imageObj.src = "http://lorempixel.com/400/200/";
    };
    
    
    // random image to show
    function getRandomInt(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    var randomNumber = getRandomInt(1, 6);
    //console.log(randomNumber);
    
    
    // script for cheking image caption with selected value
    function match() {
      var imageCaption = "car";
      var e = document.getElementById("selectList");
      var selectedObj = e.options[e.selectedIndex].value;
      if(selectedObj === "empty") {
        document.getElementById("results").innerHTML = "select your vehicle first";
      }
      else if(imageCaption == selectedObj && selectedObj != "empty") {
        //alert("match found");
        //console.log("match found");
        document.getElementById("results").innerHTML = "match found";
      }
      else {
        //alert("not this time");
        //console.log("not this time");
        document.getElementById("results").innerHTML = "not this time";
      }
      console.log(selectedObj);
    }
    
    
    //
    // amination class
    var Animation = function(canvasID) {
      this.canvas = document.getElementById(canvasID);
      this.context = this.canvas.getContext("2d");
      this.t = 0;
      this.timeInterval = 0;
      this.startTime = 0;
      this.lastTime = 0;
      this.frame = 0;
      this.animating = false;
    
      window.requestAnimFrame = (function(callback) {
        return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
          window.setTimeout(callback, 1000 / 60);
        };
      })();
    };
    // getContext method
    Animation.prototype.getContext = function() {
      return this.context;
    };
    // getCanvas method
    Animation.prototype.getCanvas = function() {
      return this.canvas;
    };
    // clear canvas method
    Animation.prototype.clear = function() {
      this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    };
    // generating frame of animation method
    Animation.prototype.setDrawStage = function() {
      this.drawStage = func;
    };
    Animation.prototype.isAnimating = function() {
      return this.animating;
    };
    // function get frame - number of frame
    Animation.prototype.getFrame = function() {
      return this.frame;
    };
    // start animation method
    Animation.prototype.start = function() {
      this.animating = true;
      var date = new Date();
      this.startTime = date.getTime();
      this.lastTime = this.startTime;
    
      if(this.drawStage !== undefined) {
        this.drawStage();
      }
      this.animationLoop();
    };
    // stop method - stop animation
    Animation.prototype.stop = function() {
      this.animating = false;
    };
    // time interval method - return time in miliseconds between last and current animation frame
    Animation.prototype.getTimeInterval = function() {
      return this.timeInterval;
    };
    // get time - return in miliseconds animation time
    Animation.prototype.getTime = function() {
      return this.t;
    };
    // get fps method - retur current animation fps value
    Animation.prototype.getFps = function() {
      return this.timeInterval > 0 ? 1000 / this.timeInterval : 0;
    };
    // animationLoop method - main animation loop
    Animation.prototype.animationLoop = function() {
      var that = this;
      this.frame++;
      var date = new Date();
      var thisTime = date.getTime();
      this.timeInterval = thisTime - this.lastTime;
      this.t += this.timeInterval;
      this.lastTime = thisTime;
    
      if(this.drawStage !== undefined) {
        this.drawStage();
      }
      if(this.animating) {
        requestAnimFrame(function() {
          that.animationLoop();
        });
      }
    };
    //// animation class end
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    
    <script type="text/javascript">
    
    </script>
    </head>
    
    <body>
      <canvas id="myCanvas" width="400" height="200"></canvas>
    
      <form action="#" method="post">
        <select id="selectList">
          <option value="empty">select vehicle</option>
          <option value="car">car</option>
          <option value="bike">bike</option>
          <option value="quad">quad</option>
          <option value="truck">truck</option>
          <option value="pickup">pickup</option>
          <option value="pogo">pogo</option>
        </select>
    
        <input type="button" value="Click to match" onClick="match()">
      </form>
    
      <p id="results"></p>
    </body>
    </html>

0 个答案:

没有答案