-2

I have a HTML5 canvas project which allows for the uploading of an image to the canvas. Then it is variously drawn on.

I can run this project locally with

$ http-server

Running this locally, I don't get any errors.

The project is on github

The issue is that in gh-pages I get the error,

Uncaught TypeError: window.addEvent is not a function
    at (index):22

Line 22 is,

   window.addEvent('load', function() {

This is also a problem when trying to run this with the snippet tool.

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title></title>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" crossorigin="anonymous">
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" crossorigin="anonymous"></script>
  <script src="https://rawgit.com/eligrey/FileSaver.js/master/FileSaver.js"></script>
  <script src="https://rawgit.com/eligrey/canvas-toBlob.js/master/canvas-toBlob.js"></script>

  <script type="text/javascript">
    var Pts = [];
    var dist;
    let inputValue;
    var ratio;
    var angle;

    window.addEvent('load', function() {
      var imageLoader = document.getElementById('imageLoader');
      imageLoader.addEventListener('change', handleImage, false);
      var c = document.getElementById('canvas');
      var ctx = c.getContext('2d');

      function handleImage(e) {
        var reader = new FileReader();
        reader.onload = function(event) {
          var img = new Image();
          img.onload = function() {
            c.width = img.width;
            c.height = img.height;
            ctx.drawImage(img, 0, 0);
          }
          img.src = event.target.result;
        }
        reader.readAsDataURL(e.target.files[0]);
      }

      $("#canvas").click(function(e) {
        getPosition(e);
      });
    });

    var pointSize = 3;

    // Event will be a click event which can be retrieved as first parameter in the addEventListener(function(event){}); or in jQuery with $("selector").click(function(event){});
    function getPosition(event) {
      var rect = canvas.getBoundingClientRect();
      var x = event.clientX - rect.left; // x == the location of the click in the document - the location (relative to the left) of the canvas in the document
      var y = event.clientY - rect.top; // y == the location of the click in the document - the location (relative to the top) of the canvas in the document

      Pts.push({
        x: x,
        y: y
      });

      if (Pts.length == 2) {
        dist = getDistance();
        addInput(Pts[1].x, Pts[1].y);
      }

      drawCoordinates(x, y);

      if (Pts.length % 2 == 0) {
        drawLine(Pts[Pts.length - 2].x, Pts[Pts.length - 2].y, Pts[Pts.length - 1].x, Pts[Pts.length - 1].y);
      };
    }

    function decimalAdjust(type, value, exp) {
      // If the exp is undefined or zero...
      if (typeof exp === 'undefined' || +exp === 0) {
        return Math[type](value);
      }
      value = +value;
      exp = +exp;
      // If the value is not a number or the exp is not an integer...
      if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
        return NaN;
      }
      // If the value is negative...
      if (value < 0) {
        return -decimalAdjust(type, -value, exp);
      }
      // Shift
      value = value.toString().split('e');
      value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
      // Shift back
      value = value.toString().split('e');
      return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
    }

    // Decimal round
    if (!Math.round10) {
      Math.round10 = function(value, exp) {
        return decimalAdjust('round', value, exp);
      };
    }

    function getDistance() {
      dist = Math.sqrt(Math.pow(Math.abs(Pts[Pts.length - 2].x - Pts[Pts.length - 1].x), 2) + Math.pow(Math.abs(Pts[Pts.length - 2].y - Pts[Pts.length - 1].y), 2));
      return dist.toFixed(2);
    }

    function drawLine(x1, y1, x2, y2) {
      var ctx = document.getElementById("canvas").getContext("2d");
      ctx.beginPath();
      ctx.moveTo(x1, y1);
      ctx.lineTo(x2, y2);
      if (Pts.length < 3) {
        ctx.strokeStyle = 'blue';
      } else {
        ctx.strokeStyle = 'black';
      }
      ctx.stroke();
      dist = getDistance();
      txt = dist * ratio;

      if (Pts.length > 2) {
        drawText(txt, x1, y1, x2, y2);
      }
    }

    function addInput(x, y) {
      var input = document.createElement('input');
      input.type = 'text';
      input.style.position = 'fixed';
      input.style.left = (x + 4) + 'px';
      input.style.top = (y + 4) + 'px';
      input.onkeydown = handleEnter;
      document.body.appendChild(input);
      input.focus();
      hasInput = true;
    }

    function handleEnter(e) {
      var keyCode = e.keyCode;
      if (keyCode === 13) {
        inputValue = this.value;
        document.body.removeChild(this);
        hasInput = false;
        ratio = inputValue / dist;
        if (Pts.length == 2) {
          drawText("reference line = " + dist * ratio, Pts[Pts.length - 2].x, Pts[Pts.length - 2].y, Pts[Pts.length - 1].x, Pts[Pts.length - 1].y);
        }
      }
    }

    function drawCoordinates(x, y) {
      var pointSize = 3; // Change according to the size of the point.
      var ctx = document.getElementById("canvas").getContext("2d");
      if (Pts.length < 3) {
        ctx.fillStyle = "blue"; // Red color
      } else {
        ctx.fillStyle = "red"; // Red color
      }
      ctx.beginPath(); //Start path
      ctx.arc(x, y, pointSize, 0, Math.PI * 2, true); // Draw a point using the arc function of the canvas with a point structure.
      ctx.fill(); // Close the path and fill.
    }

    function drawText(txt, x1, y1, x2, y2) {
      // (x,y) coordinate of text mid way between both points
      x = ((x2 + x1) / 2) + 5;
      y = ((y2 + y1) / 2) + 5;
      var ctx = document.getElementById("canvas").getContext("2d");
      ctx.save();
      ctx.textBaseline = 'top';
      ctx.textAlign = 'left';
      // ctx.font = font;
      angle = Math.atan((Math.abs(y2 - y1)) / (Math.abs(x2 - x1)));
      console.log(angle);
      ctx.translate(x, y)
      // ctx.rotate(-1 * angle);
      ctx.fillText(txt, 0, 0);
      ctx.restore();
    }

    function download_image() {
      // Dump the canvas contents to a file.
      var canvas = document.getElementById("canvas");
      var today = new Date();
      var date = today.getFullYear() + "" + (today.getMonth() + 1) + "" + "" + today.getDate() + "" + (today.getHours() - 2) + "" + today.getMinutes() + "" + today.getSeconds();
      today.getDate();
      canvas.toBlob(function(blob) {
        saveAs(blob, date + "Canvas.png");
      }, "image/png");
    };
  </script>
</head>
<style media="screen">
  upload_form {
    background-color: red;
    width: 100%;
    padding: 20px;
  }
</style>

<body>
  <div class="container">
    <div class="row">
      <div class="col-md-12 upload_form">
        <label>Image File:</label><br/>
        <input type="file" id="imageLoader" name="imageLoader" />
        <button type="button" onclick="download_image()" name="button">Save Canvas</button>
      </div>
    </div>
    <div class=row>
      <div class="col-md-12">
        <canvas id="canvas"></canvas>
      </div>
    </div>
  </div>
</body>

</html>

Any help would be greatly appreciated,

Thanks

Shane G
  • 3,129
  • 10
  • 43
  • 85
  • 1
    Where did you get `window.addEvent`? That's not a standard function – Ruan Mendes Sep 12 '17 at 00:04
  • 1
    -1 for posting a gigantic piece of code with multiple question. You should ask one question per post and you should try to break down your problem so you can reproduce it with less code. – Ruan Mendes Sep 12 '17 at 00:05
  • @JuanMendes This is the stackoverflow question I got this from https://stackoverflow.com/a/25557690/4001324 – Shane G Sep 12 '17 at 08:13
  • 1
    That page is using mootools, which adds the `addEvent` method to `window`. – Ruan Mendes Sep 12 '17 at 12:10

1 Answers1

2

I'm not sure why it works with http-server, but you should probably be using window.addEventListener instead of window.addEvent

Sidney
  • 4,495
  • 2
  • 18
  • 30