I am creating a drawing app, and using this function to download the canvas image.
function download() {
var dt = canvas.toDataURL('image/png');
this.href = dt;
};
I want to set the canvas background to white
before downloading because on mobile, the images are very distorted and black. Any ideas?
I am creating a drawing app, and using this function to download the canvas image.
function download() {
var dt = canvas.toDataURL('image/png');
this.href = dt;
};
I want to set the canvas background to white
before downloading because on mobile, the images are very distorted and black. Any ideas?
-
fillRect
? But your problem is not that simple as you express it... – Rayon Commented Apr 20, 2016 at 7:34 - any hints on how I may be able to do it? – Ali Zia Commented Apr 20, 2016 at 7:38
- Can you show us what you have tried so far ? – Rayon Commented Apr 20, 2016 at 7:40
- This code that I am trying. It is downloading the image, but by default the background is transparent. I want to convert it to white. – Ali Zia Commented Apr 20, 2016 at 7:41
-
1
I used
$('#canvas').css('background-color','#ffffff');
before downloading, but the image doesn't have a white background. – Ali Zia Commented Apr 20, 2016 at 7:50
1 Answer
Reset to default 9You may want to draw a white rectangle the size of the entire canvas, beneath the actual content of the canvas.
// get the canvas 2d context
var ctx = canvas.getContext('2d');
// set the ctx to draw beneath your current content
ctx.globalCompositeOperation = 'destination-over';
// set the fill color to white
ctx.fillStyle = 'white';
// apply fill starting from point (0,0) to point (canvas.width,canvas.height)
// these two points are the top left and the bottom right of the canvas
ctx.fillRect(0, 0, canvas.width, canvas.height);
You have to apply these lines before generating your toDataUrl() stream.
Idea taken from: http://www.mikechambers./blog/2011/01/31/setting-the-background-color-when-generating-images-from-canvas-todataurl/