0 Replies Latest reply on Mar 17, 2016 6:08 PM by adumi

    Canvas imitating the `Fit to changing viewport, while maintaining aspect ratio and no scrollbars` behavior, of 100 percent SWF

    adumi Level 1

      I would like my canvas to imitate precisely, cross browser, the behavior of 100 percent SWF, namely - while the containing window is being resized by user, the canvas will re-scale itself to fit into the new dimensions at maximum size possible, and while maintaining aspect ratio.
      I think that the behavior demonstrated in the following fits my desire:

      http://jsfiddle.net/mathheadinclouds/h8xyh/5/

      The css and html code stuff is clear but I am not sure where and how to place the Javascript code inside the html file, and in relation with the existing Javascript code already published by Animate.
      Here is the html page published, in my specific case, by Animate:

      <!DOCTYPE html>
      <html>
      <head>
      <meta charset="UTF-8">
      <title>canvas3</title>
      <!-- write your code here -->
      
      
      
      
      <script src="https://code.createjs.com/createjs-2015.11.26.min.js"></script>
      <script src="canvas3.js"></script>
      <script>
      var canvas, stage, exportRoot;
      function init() {
        // --- write your JS code here ---
      
        canvas = document.getElementById("canvas");
        images = images||{};
      
      
        var loader = new createjs.LoadQueue(false);
        loader.addEventListener("fileload", handleFileLoad);
        loader.addEventListener("complete", handleComplete);
        loader.loadManifest(lib.properties.manifest);
      }
      
      
      function handleFileLoad(evt) {
        if (evt.item.type == "image") { images[evt.item.id] = evt.result; }
      }
      
      
      function handleComplete(evt) {
        exportRoot = new lib.canvas3();
      
      
        stage = new createjs.Stage(canvas);
        stage.addChild(exportRoot);
        stage.update();
      
      
        createjs.Ticker.setFPS(lib.properties.fps);
        createjs.Ticker.addEventListener("tick", stage);
      }
      
      
      </script>
      
      
      <!-- write your code here -->
      
      
      </head>
      <body onload="init();" style="background-color:#D4D4D4;margin:0px;">
        <canvas id="canvas" width="720" height="576" style="background-color:#666666"></canvas>
      </body>
      </html>
      
      
      

       

       

       

      And that is the Javascript code copied from the above example:

       

       

       

      var vGap = 0;
      var hGap = 0;
      
      function writeSizeInfoToConsole(){
          var cw = ctx.canvas.width;
          var ch = ctx.canvas.height;
          var cssW = $(ctx.canvas).css("width");
          var cssH = $(ctx.canvas).css("height");
          var txt1 = "canvas: (w, h) = (" + cw + ", " + ch + ")";
          var txt2 = "css: (w, h) = (" + cssW + ", " + cssH + ")";
          console.log(txt1 + "     " + txt2);
      }
      
      
      var modes = {
          resizeByWidth: {
              description: "resize by width",
              afterInitCallback: function(){
                  $(ctx.canvas).css("width", "100%");
              },
              windowResizeCallback: function(){
                  // if you want to resize keeping aspect ratio the same and width 100%, you do not need to
                  // do anything on window resize. This handler is attached for the sole purpose of writing
                  // some info to the console, so you can see what is going on.
                  writeSizeInfoToConsole();
              }
          },
          messWithAspectRatio: {
              // keep both width and height to 100%, without using the canvas context to redraw
              // this necessarily messes up the aspect ratio
              description: "mess with aspect ratio",
              afterInitCallback: function(){
                  $(ctx.canvas).css("width", "100%");
              },
              windowResizeCallback: function(){
                  $(ctx.canvas).css("height", window.innerHeight - vGap);
                  writeSizeInfoToConsole();
              }
          },
          fixed: {
              // the default is to keep width and height constant (no change on window resize)
              description: "default behaviour"
          },
          redraw: {
              // redraw the picture.
              // if you want to have 100% width and height, no matter what the aspect ratio is,
              // and a slightly different picture, depending on that aspect ratio
              // you have no other choice than to redraw the canvas.
              // If you rather want the aspect ratio to be constant, and do the thing outlined in "resizeByWidth" instead,
              // you will probably want to avoid doing it this way, because it is expensive computationally.
              description: "redraw",
              windowResizeCallback: function(){
                  ctx.canvas.width = window.innerWidth - hGap;
                  ctx.canvas.height = window.innerHeight - vGap;
                  drawTestStuff();
                  writeSizeInfoToConsole();
              }
          }
      }
      modes.mess = modes.messWithAspectRatio;
      modes.resize = modes.resizeByWidth;
      
      
      
      
      var mode = modes.resizeByWidth;
      
      
      H = {
          nodeWithAtts : function(tagName, content, atts){
              if ( arguments.length < 3 ) atts = {};
              var openTag =  "<" +tagName;
              for ( var attName in atts ){
                  openTag += " ";
                  openTag += attName;
                  openTag += '="';
                  openTag += atts[attName];
                  openTag += '"';
              }
              openTag += ">";
              var closeTag =  "</" +tagName+ ">";
              return openTag + content + closeTag;
          },
          canvas : function(atts){
              var notSupportedInfo = "If you see this text, this means that your browser does not support the canvas element of HTML5. Try loading this page in a recent version of Chrome, Safari, Firefox, or IE9+.";
              notSupportedInfo = "";
              return this.nodeWithAtts("canvas", notSupportedInfo, atts);
          }
      }
      function queryStringGetParametersObject(doc){
          // retrieve get parameters from document search string,
          // result is an object (associative array) with the parameters as entries
          // or null, if the querystring is absent.
          if ( arguments.length < 1 ){
              doc = document;
          }
          // full search string
          var s = doc.location.search;
          // omit question mark
          var str = s.substr(1, s.length);
          if ( !str ) return null;
          var result = {};
          // split into name value pairs
          var arr = str.split('&');
          var numParams = arr.length;
          for ( var i=0; i<numParams; i++ ){
              // split into name and value
              var subArr = arr[i].split('=');
              var paramName = unescape(subArr[0]);
              var value = '';
              if ( subArr.length > 1 ){
                  value = unescape(subArr[1]);
              }
              // store what we have retrieved
              result[paramName] = value;
          }
          return result;
      }
      function drawTestStuff(){
          var cos = Math.cos;
          var sin = Math.sin;
          var pi = Math.PI;
          var c = ctx.canvas;
          var w = c.width;
          var h = c.height;
          ctx.fillStyle = "#ffa";
          ctx.fillRect(0, 0, w, h);
          var colors = [
              "rgba(255,0,0,0.5)",
              "rgba(0,255,0,0.5)",
              "rgba(0,0,255,0.5)"
          ];
          var s = Math.min(w,h);
          var R = s * 0.125;
          var r = s * 0.25;
          var centerX = w/2;
          var centerY = h/2;
          for (var i=0; i<3; i++){
              ctx.fillStyle = colors[i];
              ctx.beginPath();
              var angle = 2 * pi * i / 3;
              var cx = centerX + R * cos(angle);
              var cy = centerY + R * sin(angle);
              ctx.arc(cx, cy, r, 0, 2*pi);
              ctx.fill();
          }
          ctx.textAlign = "center";
          ctx.fillStyle = "black";
          ctx.font = Math.round(0.04 * w) + "pt Arial";
          var txt = "description" in mode ? mode.description : "lorem ipsum dolor sit amet";
          ctx.fillText(txt, centerX, centerY);
      }
      function retrieveModeFromGetParas(){
          o = queryStringGetParametersObject();
          if (o && "mode" in o && o.mode in modes){
              mode = modes[o.mode];
          }
      }
      function initPage(){
          retrieveModeFromGetParas();
          var body = $(document.body);
          var w = window.innerWidth - hGap;
          var h = window.innerHeight - vGap;
          var canvHtml = H.canvas({width: w, height: h, id: "canvas"});
          body.html(canvHtml);
          ctx = $("#canvas")[0].getContext('2d');
          drawTestStuff();
          if ("afterInitCallback" in mode){
              mode.afterInitCallback();
          }
          if ("windowResizeCallback" in mode){
              $(window).bind("resize", mode.windowResizeCallback);
          }
      }
      
      
      
      

      Thank you, in advance!