This week's book giveaway is in the JavaFX forum.
We're giving away four copies of Introducing JavaFX 8 Programming and have Herbert Schildt on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes How do I put an image on a canvas? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Introducing JavaFX 8 Programming this week in the JavaFX forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How do I put an image on a canvas?" Watch "How do I put an image on a canvas?" New topic

How do I put an image on a canvas?

Carlos Failde
Ranch Hand

Joined: Oct 20, 2000
Posts: 84
I have put a canvas on an applet and want to add a gif image to the canvas.
I know to put an image on an applet you'd use something like
Image I= getImage(getCodeBase(), "image.gif");
g.drawImage(I, x,y,width, height, this);
but I can't figure out how to add an image to my canvas.
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
This thread may help with your question. Basically, you will have to subclass the canvas and override its paint() method. You should be careful if you are mixing a canvas with any Swing components because you can get wierd results, as mentioned in the above thread. In that case, you can use a JPanel for drawing instead.
Sean MacLean
Ranch Hand

Joined: Nov 07, 2000
Posts: 621
You simply have to get the Graphics instance from the Canvas and draw using that. It should look something like this

Hope this helps.
It is sorta covered in the JavaRanch Style Guide.
subject: How do I put an image on a canvas?
It's not a secret anymore!