When I try to make a canvas not error but also does nothing

Asked

Viewed 57 times

1

I wish I knew 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>

2 answers

1

Some mistakes:

  • in that file I don’t see the script for Modernizr
  • the .addEventListener that will call your function is within the function itself, ie will never be called
  • corrects the syntax of if/else, I don’t see any Lse, just a block after the end statement after the return.
  • you might want to use the DOMContentLoaded, he is called before the load

Forehead 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>

0

When I work with Canvas, I don’t like to write the tag directly in the HTML file, I create a function to be responsible for it, even help in case I will use the same JS file in another document, I won’t need to rewrite the tag, since the function itself creates, and throws into 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.