View Full Version : HTML 5 Canvas Background Not Saving

11-22-2012, 03:53 PM
OK LOL, well, I want to know why when I save a canvas, the background is still transparent when I did give it a background color in CSS?

My codes was to write on a Canvas. I don't have issues in it. I only have issues about the background which is still transparent after right click on the canvas to save.


<canvas id="canvas" width="200" height="200"></canvas>
<img id="canvassave" alt="Right click to save me!">
<input type="text" size="25" id="lol"/>
<input type="button" value="write" onClick="writethecrap();"/>


#canvas {


function writethecrap () {
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var loltext = document.getElementById("lol").value;
var dataURL = canvas.toDataURL();

document.getElementById('canvassave').src = dataURL;
context.fillText(loltext, 50, 50);

Bear in mind, the text is being written, only when I save the Canvas after right-click, the background is not saving. It is transparent.

11-22-2012, 04:10 PM
This is because the background is not part of the canvas content which will be converted using .toDataURL() but rather part of the style (CSS) of the canvas (just to manipulate its screen appearance). If you want the red background to be part of the canvas, the first thing you should do after initiating the canvas is to fill it with red color.

11-22-2012, 04:33 PM
How to do it?

11-22-2012, 05:17 PM
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var width = canvas.width;
var height = canvas.height;
context.fillStyle='rgb(255,0,0)'; // red
context.fillRect(0, 0, width, height);

11-22-2012, 05:44 PM
And suppose I make the background image? How to do it and will it save the background image as well if we do it?

11-22-2012, 06:51 PM
I don't understand. Do you have a CSS background-color and a CSS background-image and something (text) in the foreground??

11-22-2012, 07:14 PM
The background is color right now. I was asking what if I want a background image now? How to do it? I know the drawimage function only.

11-22-2012, 08:10 PM
Yes, for a background-image you would need the drawImage method for the canvas. Draw the background-image first and then the foreground.

11-22-2012, 08:16 PM
I think its lame. CSS should be accepted! Anyway, thank you!