HTML 中的图片

一开始,网络只是文本,而且真的很无聊。幸运的是,不久之后就添加了在网页中嵌入图片(以及其他更有趣的内容类型)的功能。从简单的 <img> 元素开始是合乎逻辑的,该元素用于在网页中嵌入简单的图片,但还有其他类型的多媒体需要考虑。在本文中,我们将深入了解如何使用它,包括基础知识、使用 <figure> 用标题对其进行注释,并详细说明它与 CSS 背景图片的关系,并且我们将介绍可用于 Web 平台的其他图形。

¥In the beginning, the Web was just text, and it was really quite boring. Fortunately, it wasn't too long before the ability to embed images (and other more interesting types of content) inside web pages was added. It is logical to start with the humble <img> element, used to embed a simple image in a webpage, but there are other types of multimedia to consider. In this article we'll look at how to use it in depth, including the basics, annotating it with captions using <figure>, and detailing how it relates to CSS background images, and we'll introduce other graphics available to the web platform.

Multimedia and Embedding Images
先决条件: 基本软件已安装处理文件 的基础知识、熟悉 HTML 基础知识(如 HTML 入门 中所述。)
目标: 要了解如何在 HTML 中嵌入简单图片、用标题对其进行注释,以及 HTML 图片如何与 CSS 背景图片相关。

我们如何在网页上放置图片?

¥How do we put an image on a webpage?

为了在网页上放置简单的图片,我们使用 <img> 元素。这是一个 void element(意思是,它不能有任何子内容,也不能有结束标记),需要两个属性才能有用:srcaltsrc 属性包含指向要嵌入页面中的图片的 URL。与 <a> 元素的 href 属性一样,src 属性可以是相对 URL 或绝对 URL。如果没有 src 属性,img 元素就没有要加载的图片。

¥In order to put a simple image on a web page, we use the <img> element. This is a void element (meaning, it cannot have any child content and cannot have an end tag) that requires two attributes to be useful: src and alt. The src attribute contains a URL pointing to the image you want to embed in the page. As with the href attribute for <a> elements, the src attribute can be a relative URL or an absolute URL. Without a src attribute, an img element has no image to load.

alt 属性描述如下.

¥The alt attribute is described below.

注意:在继续之前,你应该阅读 URL 和路径快速入门 来刷新你对相对和绝对 URL 的记忆。

¥Note: You should read A quick primer on URLs and paths to refresh your memory on relative and absolute URLs before continuing.

例如,如果你的图片名为 dinosaur.jpg,并且它与 HTML 页面位于同一目录中,则可以像这样嵌入图片:

¥So for example, if your image is called dinosaur.jpg, and it sits in the same directory as your HTML page, you could embed the image like so:

html
<img src="dinosaur.jpg" alt="Dinosaur" />

如果图片位于 images 子目录中,该子目录与 HTML 页面位于同一目录中,那么你可以像这样嵌入它:

¥If the image was in an images subdirectory, which was inside the same directory as the HTML page, then you'd embed it like this:

html
<img src="images/dinosaur.jpg" alt="Dinosaur" />

等等。

¥And so on.

注意:搜索引擎还会读取图片文件名并将其计入 SEO。因此,你应该为图片指定一个描述性的文件名;dinosaur.jpgimg835.png 好。

¥Note: Search engines also read image filenames and count them towards SEO. Therefore, you should give your image a descriptive filename; dinosaur.jpg is better than img835.png.

你还可以使用绝对 URL 嵌入图片,例如:

¥You could also embed the image using its absolute URL, for example:

html
<img src="https://www.example.com/images/dinosaur.jpg" alt="Dinosaur" />

但是,不建议通过绝对 URL 进行链接。你应该托管要在网站上使用的图片,这在简单的设置中意味着将网站的图片与 HTML 保存在同一服务器上。此外,在维护方面,使用相对 URL 比绝对 URL 更有效(当你将站点移动到其他域时,无需更新所有 URL 以包含新域)。在更高级的设置中,你可以使用 CDN(内容分发网络) 来传送图片。

¥Linking via absolute URLs is not recommended, however. You should host the images you want to use on your site, which in simple setups means keeping the images for your website on the same server as your HTML. In addition, it is more efficient to use relative URLs than absolute URLs in terms of maintenance (when you move your site to a different domain, you won't need to update all your URLs to include the new domain). In more advanced setups, you might use a CDN (Content Delivery Network) to deliver your images.

如果你没有创建图片,则应确保你有权在发布图片的许可条件下使用它们(有关更多信息,请参阅下面的 媒体资源和许可)。

¥If you did not create the images, you should make sure you have the permission to use them under the conditions of the license they are published under (see Media assets and licensing below for more information).

警告:未经许可,切勿将 src 属性指向他人网站上托管的图片。这就是所谓的 "hotlinking"。这被认为是不道德的,因为当有人访问你的页面时,其他人将支付传输图片的带宽费用。它还会让你无法控制图片被删除或替换为令人尴尬的内容。

¥Warning: Never point the src attribute at an image hosted on someone else's website without permission. This is called "hotlinking". It is considered unethical, since someone else would be paying the bandwidth costs for delivering the image when someone visits your page. It also leaves you with no control over the image being removed or replaced with something embarrassing.

前面的代码片段,无论是绝对 URL 还是相对 URL,都会给出以下结果:

¥The previous code snippet, either with the absolute or the relative URL, will give us the following result:

A basic image of a dinosaur, embedded in a browser, with "Images in HTML" written above it

注意:诸如 <img><video> 之类的元素有时被称为替换元素。这是因为元素的内容和大小是由外部资源(如图片或视频文件)定义的,而不是由元素本身的内容定义的。你可以在 替换的元素 阅读有关它们的更多信息。

¥Note: Elements like <img> and <video> are sometimes referred to as replaced elements. This is because the element's content and size are defined by an external resource (like an image or video file), not by the contents of the element itself. You can read more about them at Replaced elements.

注意:你可以从本节 在 GitHub 上运行 中找到完成的示例(也请参阅 源代码。)

¥Note: You can find the finished example from this section running on GitHub (see the source code too.)

替代文本

¥Alternative text

我们要查看的下一个属性是 alt。它的值应该是图片的文本描述,用于图片无法看到/显示或由于互联网连接速度慢而需要很长时间才能渲染的情况。例如,我们上面的代码可以修改如下:

¥The next attribute we'll look at is alt. Its value is supposed to be a textual description of the image, for use in situations where the image cannot be seen/displayed or takes a long time to render because of a slow internet connection. For example, our above code could be modified like so:

html
<img
  src="images/dinosaur.jpg"
  alt="The head and torso of a dinosaur skeleton;
          it has a large head with long sharp teeth" />

测试 alt 文本的最简单方法是故意拼错文件名。例如,如果我们的图片名称拼写为 dinosooooor.jpg,浏览器将不会显示该图片,而是显示替代文本:

¥The easiest way to test your alt text is to purposely misspell your filename. If for example our image name was spelled dinosooooor.jpg, the browser wouldn't display the image, and would display the alt text instead:

The Images in HTML title, but this time the dinosaur image is not displayed, and alt text is in its place.

那么,为什么你会看到或需要替代文本?由于多种原因,它可以派上用场:

¥So, why would you ever see or need alt text? It can come in handy for a number of reasons:

  • 用户有视觉障碍,正在使用 屏幕阅读器 向他们朗读网页。事实上,使用替代文本来描述图片对大多数用户来说都是有用的。
  • 如上所述,文件名或路径名的拼写可能是错误的。
  • 浏览器不支持图片类型。有些人仍然使用纯文本浏览器,例如 Lynx,它显示图片的替代文本。
  • 你可能想提供文本供搜索引擎使用;例如,搜索引擎可以将替代文本与搜索查询相匹配。
  • 用户已关闭图片以减少数据传输量和干扰。这在移动调用以及带宽有限或昂贵的国家/地区尤其常见。

你到底应该在 alt 属性中写入什么内容?这首先取决于图片存在的原因。换句话说,如果你的图片不显示,你会失去什么:

¥What exactly should you write inside your alt attribute? It depends on why the image is there in the first place. In other words, what you lose if your image doesn't show up:

  • 装饰。你应该将 CSS 背景图片 用于装饰图片,但如果必须使用 HTML,请添加空白 alt=""。如果图片不是内容的一部分,屏幕阅读器不应该浪费时间阅读它。
  • 内容。如果你的图片提供了重要信息,请在简短的 alt 文本中提供相同的信息,或者更好的是,在每个人都可以看到的正文中提供相同的信息。不要写多余的 alt 文本。如果主要内容中的所有段落都写了两次,对于视力正常的用户来说会有多烦人?如果正文充分描述了图片,则可以仅使用 alt=""
  • 关联。如果你将图片放入 <a> 标签内,要将图片转换为链接,你仍然必须提供 可访问的链接文本。在这种情况下,你可以将其写入同一 <a> 元素内,或写入图片的 alt 属性内 - 以最适合你的情况为准。
  • 文本。你不应该将文本放入图片中。例如,如果你的主标题需要阴影,则使用 使用 CSS,而不是将文本放入图片中。但是,如果你确实无法避免这样做,则应该在 alt 属性内提供文本。

从本质上讲,关键是提供可用的体验,即使图片看不到。这确保所有用户不会遗漏任何内容。尝试关闭浏览器中的图片并查看效果。如果看不到图片,你很快就会意识到替代文本有多么有用。

¥Essentially, the key is to deliver a usable experience, even when the images can't be seen. This ensures all users are not missing any of the content. Try turning off images in your browser and see how things look. You'll soon realize how helpful alt text is if the image cannot be seen.

注意:有关更多信息,请参阅我们的 替代文本 指南。

¥Note: For more information, see our guide to Text Alternatives.

宽度和高度

¥Width and height

你可以使用 widthheight 属性来指定图片的宽度和高度。它们以没有单位的整数形式给出,并表示图片的宽度和高度(以像素为单位)。

¥You can use the width and height attributes to specify the width and height of your image. They are given as integers without a unit, and represent the image's width and height in pixels.

你可以通过多种方式找到图片的宽度和高度。例如,在 Mac 上你可以使用 Cmd + I 来获取图片文件的显示信息。回到我们的例子,我们可以这样做:

¥You can find your image's width and height in a number of ways. For example, on the Mac you can use Cmd + I to get the display information for the image file. Returning to our example, we could do this:

html
<img
  src="images/dinosaur.jpg"
  alt="The head and torso of a dinosaur skeleton;
          it has a large head with long sharp teeth"
  width="400"
  height="341" />

这样做有一个很好的理由。页面的 HTML 和图片是单独的资源,由浏览器作为单独的 HTTP(S) 请求获取。一旦浏览器收到 HTML,它就会开始将其显示给用户。如果尚未收到图片(通常会出现这种情况,因为图片文件大小通常比 HTML 文件大得多),则浏览器将仅呈现 HTML,并尽快使用图片更新页面 正如收到的那样。

¥There's a very good reason to do this. The HTML for your page and the image are separate resources, fetched by the browser as separate HTTP(S) requests. As soon as the browser has received the HTML, it will start to display it to the user. If the images haven't yet been received (and this will often be the case, as image file sizes are often much larger than HTML files), then the browser will render only the HTML, and will update the page with the image as soon as it is received.

例如,假设图片后面有一些文本:

¥For example, suppose we have some text after the image:

html
<h1>Images in HTML</h1>

<img
  src="dinosaur.jpg"
  alt="The head and torso of a dinosaur skeleton; it has a large head with long sharp teeth"
  title="A T-Rex on display in the Manchester University Museum" />
<blockquote>
  <p>
    But down there it would be dark now, and not the lovely lighted aquarium she
    imagined it to be during the daylight hours, eddying with schools of tiny,
    delicate animals floating and dancing slowly to their own serene currents
    and creating the look of a living painting. That was wrong, in any case. The
    ocean was different from an aquarium, which was an artificial environment.
    The ocean was a world. And a world is not art. Dorothy thought about the
    living things that moved in that world: large, ruthless and hungry. Like us
    up here.
  </p>
  <footer>- Rachel Ingalls, <cite>Mrs. Caliban</cite></footer>
</blockquote>

一旦浏览器下载了 HTML,浏览器就会开始显示该页面。

¥As soon as the browser downloads the HTML, the browser will start to display the page.

加载图片后,浏览器会将图片添加到页面。由于图片占用空间,浏览器必须将文本向下移动到页面,以适应其上方的图片:

¥Once the image is loaded, the browser adds the image to the page. Because the image takes up space, the browser has to move the text down the page, to fit the image above it:

Comparison of page layout while the browser is loading a page and when it has finished, when no size is specified for the image.

像这样移动文本会极大地分散用户的注意力,尤其是当他们已经开始阅读文本时。

¥Moving the text like this is extremely distracting to users, especially if they have already started to read it.

如果你使用 widthheight 属性在 HTML 中指定图片的实际大小,那么浏览器在下载图片之前就知道它需要留出多少空间。

¥If you specify the actual size of the image in your HTML, using the width and height attributes, then the browser knows, before it has downloaded the image, how much space it has to allow for it.

这意味着下载图片后,浏览器不必移动周围的内容。

¥This means that when the image has been downloaded, the browser doesn't have to move the surrounding content.

Comparison of page layout while the browser is loading a page and when it has finished, when the image size is specified.

有关此功能历史的优秀文章,请参阅 设置图片的高度和宽度再次很重要

¥For an excellent article on the history of this feature, see Setting height and width on images is important again.

注意:正如我们所说,尽管使用 HTML 属性指定图片的实际大小是一种很好的做法,但你不应该使用它们来调整图片大小。

¥Note: Although, as we have said, it is good practice to specify the actual size of your images using HTML attributes, you should not use them to resize images.

如果将图片尺寸设置得太大,最终会得到看起来有颗粒感、模糊或太小的图片,并且会浪费带宽来下载不符合用户需求的图片。如果你不保持正确的 纵横比,图片最终也可能看起来扭曲。在将图片放到网页上之前,你应该使用图片编辑器将图片调整为正确的尺寸。

¥If you set the image size too big, you'll end up with images that look grainy, fuzzy, or too small, and wasting bandwidth downloading an image that is not fitting the user's needs. The image may also end up looking distorted, if you don't maintain the correct aspect ratio. You should use an image editor to put your image at the correct size before putting it on your webpage.

如果你确实需要更改图片的大小,则应使用 CSS

¥If you do need to alter an image's size, you should use CSS instead.

图片标题

¥Image titles

有链接 一样,你还可以向图片添加 title 属性,以在需要时提供进一步的支持信息。在我们的示例中,我们可以这样做:

¥As with links, you can also add title attributes to images, to provide further supporting information if needed. In our example, we could do this:

html
<img
  src="images/dinosaur.jpg"
  alt="The head and torso of a dinosaur skeleton;
          it has a large head with long sharp teeth"
  width="400"
  height="341"
  title="A T-Rex on display in the Manchester University Museum" />

这为我们提供了鼠标悬停时的工具提示,就像链接标题一样:

¥This gives us a tooltip on mouse hover, just like link titles:

The dinosaur image, with a tooltip title on top of it that reads A T-Rex on display at the Manchester University Museum

但是,不建议这样做 - title 有许多可访问性问题,主要基于屏幕阅读器支持非常不可预测的事实,并且大多数浏览器不会显示它,除非你用鼠标悬停(因此例如无法访问键盘用户) )。如果你对这方面的更多信息感兴趣,请阅读 Scott O'Hara 的 称号属性的磨难

¥However, this is not recommended — title has a number of accessibility problems, mainly based around the fact that screen reader support is very unpredictable and most browsers won't show it unless you are hovering with a mouse (so e.g. no access to keyboard users). If you are interested in more information about this, read The Trials and Tribulations of the Title Attribute by Scott O'Hara.

最好将此类支持信息包含在主要文章文本中,而不是附加到图片中。

¥It is better to include such supporting information in the main article text, rather than attached to the image.

主动学习:嵌入图片

¥Active learning: embedding an image

现在轮到你玩了!这个主动学习部分将让你通过简单的嵌入练习来启动和运行。你将获得一个基本的 <img> 标签;我们希望你嵌入位于以下 URL 的图片:

¥It is now your turn to play! This active learning section will have you up and running with a simple embedding exercise. You are provided with a basic <img> tag; we'd like you to embed the image located at the following URL:

url
https://raw.githubusercontent.com/mdn/learning-area/master/html/multimedia-and-embedding/images-in-html/dinosaur_small.jpg

早些时候我们说过永远不要热链接到其他服务器上的图片,但这只是为了学习目的,所以我们就放过你一次。

¥Earlier we said to never hotlink to images on other servers, but this is just for learning purposes, so we'll let you off this one time.

我们还希望你:

¥We would also like you to:

  • 添加一些替代文本,并通过拼写错误的图片 URL 来检查其是否有效。
  • 设置图片正确的 widthheight(提示:宽 200 像素,高 171 像素),然后尝试其他值,看看效果如何。
  • 在图片上设置 title

如果你犯了错误,你可以随时使用“重置”按钮进行重置。如果你确实遇到困难,请按“显示解决方案”按钮查看答案:

¥If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see an answer:

html
<h2>Live output</h2>

<div class="output" style="min-height: 50px;"></div>

<h2>Editable code</h2>
<p class="a11y-label">
  Press Esc to move focus away from the code area (Tab inserts a tab character).
</p>

<textarea id="code" class="input" style="min-height: 100px; width: 95%">
<img>
</textarea>

<div class="playable-buttons">
  <input id="reset" type="button" value="Reset" />
  <input id="solution" type="button" value="Show solution" />
</div>
css
html {
  font-family: sans-serif;
}

h2 {
  font-size: 16px;
}

.a11y-label {
  margin: 0;
  text-align: right;
  font-size: 0.7rem;
  width: 98%;
}

body {
  margin: 10px;
  background: #f5f9fa;
}
js
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
const output = document.querySelector(".output");
const code = textarea.value;
let userEntry = textarea.value;

function updateCode() {
  output.innerHTML = textarea.value;
}

const htmlSolution =
  '<img src="https://raw.githubusercontent.com/mdn/learning-area/master/html/multimedia-and-embedding/images-in-html/dinosaur_small.jpg"\n alt="The head and torso of a dinosaur skeleton; it has a large head with long sharp teeth"\n width="200"\n height="171"\n title="A T-Rex on display in the Manchester University Museum">';
let solutionEntry = htmlSolution;

reset.addEventListener("click", () => {
  textarea.value = code;
  userEntry = textarea.value;
  solutionEntry = htmlSolution;
  solution.value = "Show solution";
  updateCode();
});

solution.addEventListener("click", () => {
  if (solution.value === "Show solution") {
    textarea.value = solutionEntry;
    solution.value = "Hide solution";
  } else {
    textarea.value = userEntry;
    solution.value = "Show solution";
  }
  updateCode();
});

textarea.addEventListener("input", updateCode);
window.addEventListener("load", updateCode);

// stop tab key tabbing out of textarea and
// make it write a tab at the caret position instead

textarea.onkeydown = (e) => {
  if (e.keyCode === 9) {
    e.preventDefault();
    insertAtCaret("\t");
  }

  if (e.keyCode === 27) {
    textarea.blur();
  }
};

function insertAtCaret(text) {
  const scrollPos = textarea.scrollTop;
  let caretPos = textarea.selectionStart;

  const front = textarea.value.substring(0, caretPos);
  const back = textarea.value.substring(
    textarea.selectionEnd,
    textarea.value.length,
  );
  textarea.value = front + text + back;
  caretPos += text.length;
  textarea.selectionStart = caretPos;
  textarea.selectionEnd = caretPos;
  textarea.focus();
  textarea.scrollTop = scrollPos;
}

// Update the saved userCode every time the user updates the text area code

textarea.onkeyup = function () {
  // We only want to save the state when the user code is being shown,
  // not the solution, so that solution is not saved over the user code
  if (solution.value === "Show solution") {
    userEntry = textarea.value;
  } else {
    solutionEntry = textarea.value;
  }

  updateCode();
};

媒体资源和许可

¥Media assets and licensing

你在网络上找到的图片(和其他媒体资源类型)是根据各种许可证类型发布的。在你正在构建的网站上使用图片之前,请确保你拥有该图片、有权使用它或遵守所有者的许可条件。

¥Images (and other media asset types) you find on the web are released under various license types. Before you use an image on a site you are building, ensure you own it, have permission to use it, or comply with the owner's licensing conditions.

了解许可证类型

¥Understanding license types

让我们看一下你可能在网络上找到的一些常见许可证类别。

¥Let's look at some common categories of licenses you are likely to find on the web.

版权所有

¥All rights reserved

歌曲、书籍或软件等原创作品的创作者通常在封闭版权保护下发布他们的作品。这意味着,默认情况下,他们(或其发布商)拥有使用(例如,展示或分发)其作品的专有权。如果你想使用具有版权所有许可的受版权保护的图片,你需要执行以下操作之一:

¥Creators of original work such as songs, books, or software often release their work under closed copyright protection. This means that, by default, they (or their publisher) have exclusive rights to use (for example, display or distribute) their work. If you want to use copyrighted images with an all rights reserved license, you need to do one of the following:

  • 获得版权所有者的明确书面许可。
  • 支付许可费才能使用它们。这可以是一次性无限制使用费用 ("royalty-free"),也可能是 "rights-managed",在这种情况下,你可能需要按时间段、地理区域、行业或媒体类型等为每次使用支付特定费用。
  • 将你的用途限制在你所在管辖范围内被视为 合理使用公平交易 的用途。

作者不需要在其作品中包含版权声明或许可条款。一旦原创作品以有形媒介创作,版权就自动存在。因此,如果你在网上找到一张图片,并且没有版权声明或许可条款,最安全的做法是假设它受版权保护并保留所有权利。

¥Authors are not required to include a copyright notice or license terms with their work. Copyright exists automatically in an original work of authorship once it is created in a tangible medium. So if you find an image online and there are no copyright notices or license terms, the safest course is to assume it is protected by copyright with all rights reserved.

宽容的

¥Permissive

如果图片是在宽松的许可下发布的,例如 MITBSD 或合适的 知识共享 (CC) 许可,则你无需支付许可费或寻求使用许可。尽管如此,你仍必须满足各种许可条件,这些条件因许可而异。

¥If the image is released under a permissive license, such as MIT, BSD, or a suitable Creative Commons (CC) license, you do not need to pay a license fee or seek permission to use it. Still, there are various licensing conditions you will have to fulfill, which vary by license.

例如,你可能必须:

¥For example, you might have to:

  • 提供图片原始来源的链接并注明其创建者。
  • 指出是否对其进行了任何更改。
  • 在与原始图片相同的许可下分享使用该图片创建的任何衍生作品。
  • 根本不分享任何衍生作品。
  • 请勿在任何商业作品中使用该图片。
  • 包含许可证副本以及使用该映像的任何版本。

你应该查阅适用的许可证,了解需要遵守的具体条款。

¥You should consult the applicable license for the specific terms you will need to follow.

注意:你可能会在许可许可的上下文中遇到术语 "copyleft"。Copyleft 许可证(例如 GNU 通用公共许可证 (GPL) 或 "相同方式分享" Creative Commons 许可证)规定衍生作品需要在与原始作品相同的许可证下发布。

¥Note: You may come across the term "copyleft" in the context of permissive licenses. Copyleft licenses (such as the GNU General Public License (GPL) or "Share Alike" Creative Commons licenses) stipulate that derivative works need to be released under the same license as the original.

Copyleft 许可证在软件世界中很重要。基本思想是,使用 Copyleft 许可项目的代码构建的新项目(称为原始软件的 "fork")也需要在相同的 Copyleft 许可证下获得许可。这确保了新项目的源代码也可供其他人研究和修改。请注意,一般来说,为软件起草的许可证(例如 GPL)不被认为是非软件作品的良好许可证,因为它们在起草时并未考虑到非软件作品。

¥Copyleft licenses are prominent in the software world. The basic idea is that a new project built with the code of a copyleft-licensed project (this is known as a "fork" of the original software) will also need to be licensed under the same copyleft license. This ensures that the source code of the new project will also be made available for others to study and modify. Note that, in general, licenses that were drafted for software, such as the GPL, are not considered to be good licenses for non-software works as they were not drafted with non-software works in mind.

浏览本节前面提供的链接,了解不同的许可证类型及其指定的条件类型。

¥Explore the links provided earlier in this section to read about the different license types and the kinds of conditions they specify.

公共字段/CC0

¥Public domain/CC0

发布到公共字段的作品有时被称为 "不保留任何权利" - 没有版权,可以在未经许可且无需满足任何许可条件的情况下使用。作品最终可以通过多种方式进入公共字段,例如版权到期或特定权利放弃。

¥Work released into the public domain is sometimes referred to as "no rights reserved" — no copyright applies to it, and it can be used without permission and without having to fulfill any licensing conditions. Work can end up in the public domain by various means such as expiration of copyright, or specific waiving of rights.

将作品置于公共字段的最有效方法之一是根据 CC0 对其进行许可,这是一种特定的知识共享许可,为此目的提供了清晰明确的法律工具。

¥One of the most effective ways to place work in the public domain is to license it under CC0, a specific creative commons license that provides a clear and unambiguous legal tool for this purpose.

使用公共字段图片时,请获取该图片属于公共字段的证据,并保留该证据作为记录。例如,截取原始来源的屏幕截图,并清楚显示许可状态,并考虑向你的网站添加一个页面,其中包含所获取的图片列表及其许可要求。

¥When using public domain images, obtain proof that the image is in the public domain and keep the proof for your records. For example, take a screenshot of the original source with the licensing status clearly displayed, and consider adding a page to your website with a list of the images acquired along with their license requirements.

搜索许可的图片

¥Searching for permissively-licensed images

你可以使用图片搜索引擎或直接从图片存储库查找项目的许可图片。

¥You can find permissive-licensed images for your projects using an image search engine or directly from image repositories.

使用你要查找的图片的描述以及相关许可条款来搜索图片。例如,搜索 "黄色恐龙" 时,将 "公共字段图片"、"公共字段图片库"、"打开许可图片" 或类似字词添加到搜索查询中。

¥Search for images using a description of the image you are seeking along with relevant licensing terms. For example, when searching for "yellow dinosaur" add "public domain images", "public domain image library", "open licensed images", or similar terms to the search query.

一些搜索引擎具有帮助你查找具有许可许可的图片的工具。例如,使用 Google 时,转到 "图片" 选项卡搜索图片,然后单击 "工具"。结果工具栏中有一个 "使用权" 下拉菜单,你可以在其中选择专门搜索知识共享许可下的图片。

¥Some search engines have tools to help you find images with permissive licenses. For example, when using Google, go to the "Images" tab to search for images, then click "Tools". There is a "Usage Rights" dropdown in the resulting toolbar where you can choose to search specifically for images under creative commons licenses.

图片存储库站点(例如 弗利克ShutterStock皮克斯)具有搜索选项,允许你仅搜索许可的图片。有些网站专门分发许可的图片和图标,例如 苦味基名词项目

¥Image repository sites, such as Flickr, ShutterStock, and Pixabay, have search options to allow you to search just for permissively-licensed images. Some sites exclusively distribute permissively-licensed images and icons, such as Picryl and The Noun Project.

遵守发布图片所依据的许可证需要查找许可证详细信息、阅读来源提供的许可证或说明页面,然后按照这些说明进行操作。信誉良好的图片存储库使其许可条件清晰且易于查找。

¥Complying with the license the image has been released under is a matter of finding the license details, reading the license or instruction page provided by the source, and then following those instructions. Reputable image repositories make their license conditions clear and easy to find.

用图形和图形标题注释图片

¥Annotating images with figures and figure captions

说到标题,你可以通过多种方式为图片添加标题。例如,没有什么可以阻止你这样做:

¥Speaking of captions, there are a number of ways that you could add a caption to go with your image. For example, there would be nothing to stop you from doing this:

html
<div class="figure">
  <img
    src="images/dinosaur.jpg"
    alt="The head and torso of a dinosaur skeleton;
            it has a large head with long sharp teeth"
    width="400"
    height="341" />

  <p>A T-Rex on display in the Manchester University Museum.</p>
</div>

还行吧。它包含你需要的内容,并且可以使用 CSS 很好地设置样式。但这里有一个问题:没有任何东西可以在语义上将图片与其标题链接起来,这可能会给屏幕阅读器带来问题。例如,当你有 50 张图片和标题时,哪个标题与哪个图片搭配?

¥This is OK. It contains the content you need, and is nicely stylable using CSS. But there is a problem here: there is nothing that semantically links the image to its caption, which can cause problems for screen readers. For example, when you have 50 images and captions, which caption goes with which image?

更好的解决方案是使用 HTML <figure><figcaption> 元素。这些正是为了这个目的而创建的:为图形提供语义容器,并将图形清晰地链接到标题。我们上面的例子可以重写如下:

¥A better solution, is to use the HTML <figure> and <figcaption> elements. These are created for exactly this purpose: to provide a semantic container for figures, and to clearly link the figure to the caption. Our above example could be rewritten like this:

html
<figure>
  <img
    src="images/dinosaur.jpg"
    alt="The head and torso of a dinosaur skeleton;
            it has a large head with long sharp teeth"
    width="400"
    height="341" />

  <figcaption>
    A T-Rex on display in the Manchester University Museum.
  </figcaption>
</figure>

<figcaption> 元素告诉浏览器和辅助技术,标题描述了 <figure> 元素的其他内容。

¥The <figcaption> element tells browsers, and assistive technology that the caption describes the other content of the <figure> element.

注意:从可访问性的角度来看,标题和 alt 文本具有不同的作用。字幕甚至可以让能够看到图片的人受益,而 alt 文本提供与缺失图片相同的功能。因此,标题和 alt 文本不应该只是说同样的事情,因为它们都会在图片消失时出现。尝试在浏览器中关闭图片并查看其外观。

¥Note: From an accessibility viewpoint, captions and alt text have distinct roles. Captions benefit even people who can see the image, whereas alt text provides the same functionality as an absent image. Therefore, captions and alt text shouldn't just say the same thing, because they both appear when the image is gone. Try turning images off in your browser and see how it looks.

图形不一定是图片。它是一个独立的内容单元:

¥A figure doesn't have to be an image. It is an independent unit of content that:

  • 以简洁、易于理解的方式表达你的意思。
  • 可以进入页面线性流中的多个位置。
  • 提供支持正文的基本信息。

图形可以是多张图片、代码片段、音频、视频、方程式、表格或其他内容。

¥A figure could be several images, a code snippet, audio, video, equations, a table, or something else.

主动学习:创建一个图形

¥Active learning: creating a figure

在这个主动学习部分,我们希望你从之前的主动学习部分中获取完成的代码,并将其转换为图形:

¥In this active learning section, we'd like you to take the finished code from the previous active learning section, and turn it into a figure:

  1. 将其包裹在 <figure> 元素中。
  2. 将文本复制出 title 属性,删除 title 属性,然后将文本放入图片下方的 <figcaption> 元素内。

如果你犯了错误,你可以随时使用“重置”按钮进行重置。如果你确实遇到困难,请按“显示解决方案”按钮查看答案:

¥If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see an answer:

html
<h2>Live output</h2>

<div class="output" style="min-height: 50px;"></div>

<h2>Editable code</h2>
<p class="a11y-label">
  Press Esc to move focus away from the code area (Tab inserts a tab character).
</p>

<textarea
  id="code"
  class="input"
  style="min-height: 100px; width: 95%"></textarea>

<div class="playable-buttons">
  <input id="reset" type="button" value="Reset" />
  <input id="solution" type="button" value="Show solution" />
</div>
css
html {
  font-family: sans-serif;
}

h2 {
  font-size: 16px;
}

.a11y-label {
  margin: 0;
  text-align: right;
  font-size: 0.7rem;
  width: 98%;
}

body {
  margin: 10px;
  background: #f5f9fa;
}
js
const textarea = document.getElementById("code");
const reset = document.getElementById("reset");
const solution = document.getElementById("solution");
const output = document.querySelector(".output");
const code = textarea.value;
let userEntry = textarea.value;

function updateCode() {
  output.innerHTML = textarea.value;
}

const htmlSolution =
  '<figure>\n <img src="https://raw.githubusercontent.com/mdn/learning-area/master/html/multimedia-and-embedding/images-in-html/dinosaur_small.jpg"\n alt="The head and torso of a dinosaur skeleton; it has a large head with long sharp teeth"\n width="200"\n height="171">\n <figcaption>A T-Rex on display in the Manchester University Museum</figcaption>\n</figure>';
let solutionEntry = htmlSolution;

reset.addEventListener("click", () => {
  textarea.value = code;
  userEntry = textarea.value;
  solutionEntry = htmlSolution;
  solution.value = "Show solution";
  updateCode();
});

solution.addEventListener("click", () => {
  if (solution.value === "Show solution") {
    textarea.value = solutionEntry;
    solution.value = "Hide solution";
  } else {
    textarea.value = userEntry;
    solution.value = "Show solution";
  }
  updateCode();
});

textarea.addEventListener("input", updateCode);
window.addEventListener("load", updateCode);

// stop tab key tabbing out of textarea and
// make it write a tab at the caret position instead

textarea.onkeydown = (e) => {
  if (e.keyCode === 9) {
    e.preventDefault();
    insertAtCaret("\t");
  }

  if (e.keyCode === 27) {
    textarea.blur();
  }
};

function insertAtCaret(text) {
  const scrollPos = textarea.scrollTop;
  let caretPos = textarea.selectionStart;

  const front = textarea.value.substring(0, caretPos);
  const back = textarea.value.substring(
    textarea.selectionEnd,
    textarea.value.length,
  );
  textarea.value = front + text + back;
  caretPos += text.length;
  textarea.selectionStart = caretPos;
  textarea.selectionEnd = caretPos;
  textarea.focus();
  textarea.scrollTop = scrollPos;
}

// Update the saved userCode every time the user updates the text area code

textarea.onkeyup = () => {
  // We only want to save the state when the user code is being shown,
  // not the solution, so that solution is not saved over the user code
  if (solution.value === "Show solution") {
    userEntry = textarea.value;
  } else {
    solutionEntry = textarea.value;
  }

  updateCode();
};

CSS 背景图片

¥CSS background images

你还可以使用 CSS 将图片嵌入网页(和 JavaScript,但这完全是另一个故事)。CSS background-image 属性和其他 background-* 属性用于控制背景图片放置。例如,要在页面上的每个段落上放置背景图片,你可以这样做:

¥You can also use CSS to embed images into webpages (and JavaScript, but that's another story entirely). The CSS background-image property, and the other background-* properties, are used to control background image placement. For example, to place a background image on every paragraph on a page, you could do this:

css
p {
  background-image: url("images/dinosaur.jpg");
}

由此产生的嵌入图片可以说比 HTML 图片更容易定位和控制。那么为什么要为 HTML 图片烦恼呢?正如上面所暗示的,CSS 背景图片仅用于装饰。如果你只是想向页面添加一些漂亮的内容以增强视觉效果,那么这很好。然而,这样的图片根本没有语义意义。它们不能有任何等效文本,对屏幕阅读器来说是不可见的,等等。这就是 HTML 图片的闪光点!

¥The resulting embedded image is arguably easier to position and control than HTML images. So why bother with HTML images? As hinted to above, CSS background images are for decoration only. If you just want to add something pretty to your page to enhance the visuals, this is fine. Though, such images have no semantic meaning at all. They can't have any text equivalents, are invisible to screen readers, and so on. This is where HTML images shine!

加起来:如果图片对你的内容有意义,你应该使用 HTML 图片。如果图片纯粹是装饰,则应该使用 CSS 背景图片。

¥Summing up: if an image has meaning, in terms of your content, you should use an HTML image. If an image is purely decoration, you should use CSS background images.

注意:你将在我们的 CSS 主题中了解更多有关 CSS 背景图片 的信息。

¥Note: You'll learn a lot more about CSS background images in our CSS topic.

网络上的其他图形

¥Other graphics on the web

我们已经看到,静态图片可以使用 <img> 元素来显示,或者通过使用 background-image 属性设置 HTML 元素的背景来显示。你还可以即时构建图形,或事后操作图片。该浏览器提供了使用代码创建 2D 和 3D 图形的方法,以及包含来自上传文件的视频或来自用户相机的实时流式视频。以下是深入了解这些更高级图形主题的文章链接:

¥We've seen that static images can be displayed using the <img> element, or by setting the background of HTML elements using the background-image property. You can also construct graphics on-the-fly, or manipulate images after the fact. The browser offers ways of creating 2D and 3D graphics with code, as well as including video from uploaded files or live streamed from a user's camera. Here are links to articles that provide insight into these more advanced graphics topics:

Canvas

<canvas> 元素提供使用 JavaScript 绘制 2D 图形的 API。

SVG

可缩放矢量图形 (SVG) 允许你使用直线、曲线和其他几何形状来渲染 2D 图形。使用矢量,你可以创建可以清晰缩放到任何尺寸的图片。

WebGL

WebGL API 指南将帮助你开始使用 WebGL,这是一种用于 Web 的 3D 图形 API,可让你在 Web 内容中使用标准 OpenGL ES。

使用 HTML 音频和视频

就像 <img> 一样,你可以使用 HTML 将 <video><audio> 嵌入到网页中并控制其播放。

WebRTC

WebRTC 中的 RTC 代表实时通信,这是一种能够在浏览器客户端(对等点)之间实现音频/视频流和数据共享的技术。

测试你的技能!

¥Test your skills!

你已读完本文,但你还记得最重要的信息吗?在继续之前,你可以找到一些进一步的测试来验证你是否已保留此信息 - 请参阅 测试你的技能:HTML 图片

¥You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see Test your skills: HTML images.

概括

¥Summary

目前为止就这样了。我们已经详细介绍了图片和标题。在下一篇文章中,我们将进一步探讨如何使用 HTML 将 视频和音频内容 嵌入网页中。

¥That's all for now. We have covered images and captions in detail. In the next article, we'll move it up a gear, looking at how to use HTML to embed video and audio content in web pages.