最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I set the canvas background before downloading - Stack Overflow

programmeradmin6浏览0评论

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?

Share Improve this question asked Apr 20, 2016 at 7:32 Ali ZiaAli Zia 3,8755 gold badges33 silver badges82 bronze badges 6
  • 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
 |  Show 1 more ment

1 Answer 1

Reset to default 9

You 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/

发布评论

评论列表(0)

  1. 暂无评论