Reputation: 151
I have all the code worked out to draw on a canvas in a separate .js
file, so now I just need to put the image on.
I can’t get the image to work, though, the normal method isn’t working. I’ve tried this:
var canvasvar;
var contextvar;
canvasvar = document.getElementById("canvas");
contextvar = canvas.getContext("2d");
var imageObj = new Image();
imageObj.src = "http://wannabevc.files.wordpress.com/2010/09/im-cool.jpg";
contextvar.drawImage(imageObj,10,10);
For one thing, should I put this inside the html
file, inside a <script></script>
at the end, or should I put it in the js
file that has the “draw stuff” code? I can’t get either to work, it runs with no errors but I don’t see any image over the canvas. So I can still draw, but no image appears. I’m guessing the image is under the canvas or something.
I’m guessing this is because I didn’t just make a canvas – I made it with all this programming happening inside it in another js
file.
I also tried putting this code inside the initCanvas
function in my .js
code. This is what actually creates the canvas. Here is the code of initCanvas
function:
// Retrieve canvas reference
canvas = document.getElementById("canvas");
// Size canvas
canvas.width = 600;
canvas.height = 400;
// Retrieve context reference, used to execute canvas drawing commands
context = canvas.getContext('2d');
context.lineCap = "round";
// Set control panel defaults
document.getElementById("thickness").selectedIndex = 0;
document.getElementById("color").selectedIndex = 1;
// Overlay image over the canvas. THIS PART IS WHAT I'M ASKING ABOUT. This is usually
// not in the code
var canvasvar;
var contextvar;
canvasvar = document.getElementById("canvas");
contextvar = canvas.getContext("2d");
var imageObj = new Image();
imageObj.src = "http://wannabevc.files.wordpress.com/2010/09/im-cool.jpg";
contextvar.drawImage(imageObj,10,10);
So the last part in this code is what I’m talking about. It isn’t working, though.
Upvotes: 0
Views: 2673
Reputation: 1
You used 'canvas' instead of 'canvasvar' when initializing the context. You should instead write 'contextvar = canvasvar.getContext('2d')'
Upvotes: 0
Reputation: 105035
Give your image time to load using imageObj.onload
var canvasvar = document.getElementById("canvas");
var contextvar = canvas.getContext("2d");
var imageObj = new Image();
imageObj.onload=function(){
contextvar.drawImage(imageObj,10,10);
}
imageObj.src = "http://wannabevc.files.wordpress.com/2010/09/im-cool.jpg";
Upvotes: 2