When I try to make a canvas, it does not do the error but also does nothing

1

I'd like to know what I'm doing wrong here ...

<script type="text/javascript">
  function draw() {
    if (!Modernizr.canvas) return; {
      var canvas = document.getElementById("mycanvas");
      var ctx = canvas.getContext("2d");
      ctx.fillStyle = "#ff0000";
      ctx.fillRect(10, 10, 200, 100);
    }
    window.addEventListener("load", draw, false);
  }
</script>

<canvas id="mycanvas"></canvas>
    
asked by anonymous 05.05.2017 / 21:49

2 answers

1

Some errors:

  • In this file I do not see the script of Modernizr
  • the .addEventListener that will call your function is inside the function itself, ie it will never be called
  • fixes the syntax of if/else , I do not see any else, just a block after the end statement after return .
  • You may want to use DOMContentLoaded , it is called before load

Test like this:

<script type="text/javascript">
  function draw() {
    var canvas = document.getElementById("mycanvas");
    var ctx = canvas.getContext("2d");
    ctx.fillStyle = "#ff0000";
    ctx.fillRect(10, 10, 200, 100);
  }
  window.addEventListener("load", draw, false);
</script>

<canvas id="mycanvas"></canvas>
    
05.05.2017 / 21:55
0

When I go to work with Canvas, I do not like to write the direct tag in the HTML file, I create a function to be responsible for it, even if I use the same JS file in another document, I will not need to rewrite the tag , since the function itself creates, and launches in the body of the document, I hope it helps

<script type="text/javascript">
  (function() {

    var canvas, ctx, lar = alt = 300;

    function writeCanvas() {
      canvas = document.createElement('canvas');
      canvas.width  = lar;
      canvas.height = alt;
      canvas.innerHTML = "Elemento não suportado";

      document.body.appendChild(canvas);

      ctx = canvas.getContext('2d');

      drawRect('red', 0, 0, canvas.width, canvas.height);
    };

    function drawRect (color, x0, y0, x1, y1) {
      ctx.fillStyle = color;
      ctx.fillRect(x0, y0, x1, y1);
    };




    writeCanvas();
  } ());
</script>
    
09.06.2017 / 07:38