javascript 使用 createElement('img') 获取 .jpeg 而不是 .png

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7561215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:32:44  来源:igfitidea点击:

Using createElement('img') to get .jpeg instead of .png

javascriptjquery

提问by Jason Kim

I would like to use createElement("img') to create .jpeg extension instead of .png

我想使用 createElement("img') 创建 .jpeg 扩展名而不是 .png

According to Flanagan's book JavaScript: The Definitive Guide: Activate Your Web Pages By David Flanagan,

根据 Flanagan 的书 JavaScript: The Definitive Guide: Activate Your Web Pages By David Flanagan,

For jpeg image type, the second argument should be a number between 0 and 1 specifying the image quality level.

对于 jpeg 图像类型,第二个参数应该是一个介于 0 和 1 之间的数字,用于指定图像质量级别。

I am not sure what the syntax for the code would be.

我不确定代码的语法是什么。

Is it something like this?

它是这样的吗?

createElement("img",1)

回答by James

The book is talking about html5's canvas tag and specifically its .toDataURL method.

这本书谈论的是 html5 的 canvas 标签,特别是它的 .toDataURL 方法。

I think you want to do something like:

我想你想做这样的事情:

var img = document.createElement('img');
img.src = 'myImageSource.jpg';

In this case, it's up to the web server to deliver the image and its type information to the web browser.

在这种情况下,由 Web 服务器将图像及其类型信息传送到 Web 浏览器。

回答by James

The bookthat you're referring to seems to be talking about the toDataURLmethod of the canvasAPI (see this), which accepts typeand qualityarguments.

您所指的这本书似乎在谈论API的toDataURL方法canvas请参阅此),它接受typequality参数。

You can use document.createElementwithout worrying about MIME types or quality.

您可以使用document.createElement而无需担心 MIME 类型或质量。

回答by foysal sheykh

you can use setAttrebure() Method or built-in 'src' property.

您可以使用 setAttrebure() 方法或内置的 'src' 属性。

var img = document.createElement('img');
img.setAttibute('src', 'img.jpg');
document.body.appendChild(img);

or use

或使用

 var img = document.createElement('img');
 img.src = "img.jpg";
 document.body.appendChild(img);