Share via


如何显示图像 (HTML)

[ 本文适用于编写 Windows 运行时应用的 Windows 8.x 和 Windows Phone 8.x 开发人员。如果你要针对 Windows 10 进行开发,请参阅 最新文档 ]

canvas 元素是 HTML 文档的可绘制区域,可以使用 JavaScript 收集图形(如动画、图表和游戏)。本主题首先介绍使用 canvas 元素显示图像所需的步骤。

先决条件

本主题假设你:

  • 可以创建使用 JavaScript 的基本 Windows 应用商店应用,该应用使用 Windows JavaScript 库模板。
  • 对 HTML 和 JavaScript 有基本的了解。

有关创建第一个采用 JavaScript 的 Windows 应用商店应用的说明,请参阅创建第一个采用 JavaScript 的 Windows 应用商店应用。有关使用 WinJS 模板的说明,请参阅“如何获取和使用 WinJS 工具包”。

说明

步骤 1: 获取呈现上下文

在将图像绘制到画布上之前,需要从 canvas 元素中获取呈现上下文。呈现上下文是用来定义绘制方法和属性的位置。由于每个 <canvas> 元素都有相关的呈现上下文(通过给出变量名称 ctx),因此,除非该页面完全加载(即,canvas 元素隐藏到 DOM 中),否则我们无法访问此上下文。确保 canvas 元素可从 DOM 使用的一种方法就是将脚本块放在页面末尾,如下所示:

<!DOCTYPE html>
<html>

<head>
  <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
  <title>Canvas element image drawing</title>
  <style>
    .
    .
    .
  </style>
</head>

<body>
  .
  .
  .
  <script>
    .   
    .
    .
  </script>
</body>

</html>

现在,我们可以按如下方式获取呈现上下文:

<!DOCTYPE html>
<html>

<head>
  <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
  <title>Canvas element image drawing</title>
  <style>
    canvas {
      border: 1px black solid; /* Draw a border around the canvas element. */
    }
  </style>
</head>

<body>
  <canvas width="491" height="538">Canvas is not supported - upgrade your browser.</canvas>
  <script>
    var ctx = (document.getElementsByTagName('canvas')[0]).getContext('2d');   
  </script>
</body>

</html>

正如我们所看到的那样,canvas 元素应当是大小为 491pxx538px 的图像。我们通过以下方法获取上下文 (ctx):获取 DOM 中所有 Canvas 元素的列表、选取第一个(也是唯一一个)元素,然后通过调用 getContext('2d') 获取第一个元素的上下文。

步骤 2: 加载要显示的图像

由于将图像下载到客户端可能需要相当长的时间,因此我们只应当在它们完全加载之后才能访问它们。这可以通过使用图像对象的 onload 事件处理程序来完成,如下所示:


var imageToDraw = new Image();

imageToDraw.onload = function() {
  // It is now safe to access the image.
}

imageToDraw.src = 'images/duckCat.jpg';

在本示例中,匿名函数仅在其相关图像 (duckCat.jpg) 完全加载之后进行调用。

步骤 3: 显示图像

通过使用 onload 事件处理程序,我们可以在画布上显示图像,如下所示:


<!DOCTYPE html>
<html>

<head>
  <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
  <title>Canvas element image drawing</title>
  <style>
    body {
      width: 402px; /* Accommodate the 1px canvas borders. */
      margin: 0 auto; /* Center the page's content. */
    }
    
    h1 {
      text-align: center;
    }
       
    canvas {
      border: 1px black solid; /* Draw a border around the canvas element. */
    }
  </style>
</head>

<body>
  <h1>How to display an image using the canvas element</h1>
  <canvas width="491" height="538">Canvas is not supported - upgrade your browser.</canvas>
  <script>
    var ctx = (document.getElementsByTagName('canvas')[0]).getContext('2d');    
    var imageToDraw = new Image();

    imageToDraw.onload = function() {
      ctx.drawImage(imageToDraw, 0, 0);
    }
    
    imageToDraw.src = 'images/duckCat.jpg';    
  </script>
</body>

</html>

备注

drawImage 方法接受的参数数量比上一个示例中显示的多,该方法具有丰富的功能。有关详细信息,请参阅 Mozilla 开发人员网络网站上的使用图像

相关主题

快速入门:绘制到画布

优化性能:JavaScript 代码