Alexander
Alexander

Reputation: 171

Html5 canvas not drawing in Div with jquery

Ok. so basically i have a div that i want to load it with a file that has some html5 canvas. When i load the file on its self it works. The problem is when i load my site normal and press the link to load the same file in the div that i want it doesn't draw.

I use $('#container').load('mycanvas.html'); with .click event to load the file

The code below is what is in the mycanvas.html file.

<style>
  body {
    margin: 0px;
    padding: 0px;
  }
  #myCanvas {
    border: 1px solid #9C9898;
  }
</style>
<script>
  window.onload = function() {
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext("2d");

    context.beginPath();
    context.moveTo(100, 150);
    context.lineTo(450, 50);
    context.stroke();
  };

</script>

<canvas id="myCanvas" width="500" height="200"></canvas>

What am i doing wrong ?

Upvotes: 1

Views: 2696

Answers (2)

Dave Hogan
Dave Hogan

Reputation: 3221

Try this for mycanvas.html.

<style>
  body {
    margin: 0px;
    padding: 0px;
  }
  #myCanvas {
    border: 1px solid #9C9898;
  }
</style>

<canvas id="myCanvas" width="500" height="200"></canvas>

<script>
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext("2d");

    context.beginPath();
    context.moveTo(100, 150);
    context.lineTo(450, 50);
    context.stroke();

</script>

Upvotes: 3

Vijay Verma
Vijay Verma

Reputation: 3698

Put

<canvas id="myCanvas" width="500" height="200"></canvas>

above the your javascript code.

Upvotes: 0

Related Questions