试试这个:
http://web.archive.org/web/20120830003356/http://www.bytestrom.eu/blog/2009/1120a_jpeg_encoder_for_javascript
下载 JPEGEncoder 后,插入以下代码:
var encoder = new JPEGEncoder();
var imageData = encoder.encode(canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height), 100);
或者
如果背景颜色有问题,试试这个:
http://www.mikechambers.com/blog/2011/01/31/setting-the-background-color-when-generating-images-from-canvas-todataurl/?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+MikeChambers+ %28迈克+钱伯斯%29
function canvasToImage(canvas, backgroundColor)
{
//cache height and width
var w = canvas.width;
var h = canvas.height;
var context = canvas.getContext('2d');
var data;
if(backgroundColor)
{
//get the current ImageData for the canvas.
data = context.getImageData(0, 0, w, h);
//store the current globalCompositeOperation
var compositeOperation = context.globalCompositeOperation;
//set to draw behind current content
context.globalCompositeOperation = "destination-over";
//set background color
context.fillStyle = backgroundColor;
//draw background / rect on entire canvas
context.fillRect(0,0,w,h);
}
//get the image data from the canvas
var imageData = canvas.toDataURL("image/png");
if(backgroundColor)
{
//clear the canvas
context.clearRect (0,0,w,h);
//restore it with original / cached ImageData
context.putImageData(data, 0,0);
//reset the globalCompositeOperation to what it was
context.globalCompositeOperation = compositeOperation;
}
//return the Base64 encoded data url string
return imageData;
}
- 背景色参数:
'rgba(255,255,255,0.5)'