简体   繁体   English

没有Alpha通道的画布toDataURL

[英]Canvas toDataURL without alpha channel

I'd like to resize uploaded images in browser. 我想在浏览器中调整上传图片的大小。 I am using canvas to draw the uploaded image to canvas and then resize it, and use the result from toDataURL method. 我正在使用画布将上载的图像绘制到画布上,然后调整其大小,并使用toDataURL方法的结果。

Simplified code (without upload parts) looks something like this: 简化的代码(没有上载部分)如下所示:

var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d', { alpha: false} );
// img src contains data url of uploaded image
ctx.drawImage(img, 0, 0, imgWidth, imgHeight); 
var dataUrl = canvas.toDataURL('image/png');

The problem is dataUrl contains alpha channel, although context was created with alpha set to false. 问题是dataUrl包含alpha通道,尽管上下文是在alpha设置为false的情况下创建的。

Is it possible to get data url without the alpha channel? 是否可以在没有Alpha通道的情况下获取数据网址?

If not, I considered using one of Javascript image libraries, but most of them rely on canvas. 如果没有,我考虑使用Javascript图像库之一,但是其中大多数依赖于canvas。

Also, I could encode the image using data in canvas, but I'd rather not do that :) 另外,我可以使用画布中的数据对图像进行编码,但我不想这样做:)

alpha:false is only used in WebGL. alpha:false仅在WebGL中使用。 It's ignored when creating a 2d context. 创建2d上下文时将忽略它。

But you can export the canvas in jpg format where your unwanted alpha is eliminated: 但是您可以将jpg格式的画布导出,从而消除了不需要的Alpha:

// export a full-quality jpg dataUrl

canvas.toDataURL("image/jpeg", 1.0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM