1

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 ?

4
  • Can we see the code for your other page with the #container. Does your browsers console window show any error message? Commented Oct 12, 2012 at 12:37
  • I am not getting any errors .. the #container div is '<div id='container'></div>' the page is to huge to post Commented Oct 12, 2012 at 12:42
  • 1
    Ok - I assume you have jQuery referenced correctly. I suspect it's something to do with window.onload = function() not running when loaded via jQuery.Load(); Commented Oct 12, 2012 at 12:51
  • Thanks for your time Dave.. i have removed the onload part from the canvas script and it works ! Commented Oct 12, 2012 at 12:53

2 Answers 2

3

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>
Sign up to request clarification or add additional context in comments.

2 Comments

If you're loading this in with ajax, I recommend putting the javascript in a closure so it won't affect the global scope.
Great point. @Alexander Wrap up the contents up in a function to help prevent the variables canvas and context interfering with other variables. These don't need to be globally accessible.
0

Put

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

above the your javascript code.

1 Comment

Try removing the window.onload part. I guess the event isn't firing?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.