HTML5 キャンバスの概要_html5 チュートリアルのヒント

WBOY
リリース: 2016-05-16 15:51:21
オリジナル
1380 人が閲覧しました

は、スクリプト言語 (通常は JavaScript) を使用してグラフィックを描画するために使用できる新しい HTML 要素です。たとえば、これを使用して、絵を描いたり、画像を合成したり、単純な (それほど単純ではない) アニメーションを実行したりできます。右側の画像は、このチュートリアル全体で使用する の実装の例を示しています。

は、最初に Apple の Mac OS X ダッシュボードに導入され、その後 Safari で使用されました。 Firefox 1.5 などの Gecko 1.8 ベースのブラウザも、この新しい要素をサポートします。 要素は、HTML 5 標準仕様としても知られる WhatWG Web アプリケーション 1.0 の一部です。

このチュートリアルでは、独自の Web ページで 要素を使用する方法を説明します。提供されている例は、 で何ができるかを明確に理解できるはずです。これらの例は、 の独自のアプリケーションの開始点としても機能します。

始める前に
HTML と JavaScript の基本的な知識がある限り、 要素の使用は難しくありません。

上で述べたように、すべての最新のブラウザが 要素をサポートしているわけではないため、サンプル アクションをすべて表示するには、Firefox 1.5 以降、または Opera 9 などの別の Gecko ベースのブラウザ、または Safari の最新バージョンが必要です。

<キャンバス>要素

要素自体を見てみましょう。
要素の定義から始めましょう。

<canvas id="tutorial" width="150" height="150"></canvas>
ログイン後にコピー

これは 要素によく似ていますが、唯一の違いは、src 属性と alt 属性がないことです。 ;canvas> は に非常に似ていますが、唯一の違いは src 属性と alt 属性が含まれていないことです。 要素には、widthheight の 2 つの属性しかありません。これらは両方ともオプションであり、DOM プロパティまたは CSS ルールを使用して設定することもできます。プロパティは widthheight の 2 つだけです。どちらもオプションであり、DOM または CSS を使用して設定できます。幅と高さの属性が指定されていない場合、キャンバスは最初に幅 300 ピクセル、高さ 150 ピクセル になります。幅と高さの属性が指定されていない場合、デフォルトは 300 です。幅 高さ 150 ピクセル 。要素のサイズは CSS によって任意に変更できますが、レンダリング中に画像はレイアウト サイズに合わせて拡大縮小されます (レンダリングが歪んでいるように見える場合は、 属性で幅と高さの属性を明示的に指定してみてください。キャンバスのサイズは CSS で調整できますが、レンダリングされた画像はレイアウトに合わせて拡大縮小されます (レンダリング結果が変形して見える場合は、CSS のみに依存する必要はありません)キャンバスの幅と高さの属性値を明示的に指定してみることができます。

id 属性は 要素に固有のものではありませんが、(ほぼ) すべての HTML 要素 (< など) に適用できるデフォルトの HTML 属性の 1 つです。 🎜>class など)、スクリプト内で ID を識別しやすくなるため、常に ID を指定することをお勧めします。
id 属性は < ではありません。 Canvas> ; 排他的で、標準の HTML タグと同様に、どの HTML 要素でも id 値を指定できます。一般に、要素に id を割り当てると、スクリプトでの使用が容易になります。

要素は、通常の画像 (余白、境界線、背景など) と同じようにスタイル設定できますが、これらのルールはキャンバス上の実際の描画には影響しません。このチュートリアルの後半でこれがどのように行われるかを参照してください。キャンバスにスタイル ルールが適用されていない場合、 要素は通常の画像と同様にスタイル設定できます (マージン、ボーダー、背景など)。ただし、これらのスタイルは、キャンバスによって生成される実際の画像には影響しません。次にスタイルを適用する方法を見ていきます。スタイルが指定されていない場合、キャンバスはデフォルトで完全に透明になります。

代替コンテンツ

要素はまだ比較的新しく、一部のブラウザ (Firefox 1.0 や Internet Explorer など) には実装されていないため、ブラウザが実装していない場合にフォールバック コンテンツを提供する手段が必要です。この要素はサポートされていません。

因为 相对较新,有些浏览器并没实现,如Firefox 1.0 和 Internet Explorer,所以我们需要为那些不支持canvas的浏览器提供替用显示内容。

Luckily this is very straightforward: we just provide alternative content inside the canvas element. Browsers who don't support it will ignore the element completely and render the fallback content, others will just render the canvas normally.
For instance we could provide a text description of the canvas content or provide a static image of the dynamically rendered content. This can look something like this:

我们只需要直接在canvas元素内插入替用内容即可。不支持canvas的浏览器会忽略canvas元素而直接渲染替用内容,而支持的浏览器则会正常地渲染canvas。例如,我们可以把一些文字或图片填入canvas内,作为替用内容:

<canvas id="stockGraph" width="150" height="150">
  current stock price: $3.15 +0.15
</canvas>

<canvas id="clock" width="150" height="150">
  <img src="images/clock.png" width="150" height="150"/>
</canvas>
ログイン後にコピー

结束标签 是必须的

In the Apple Safari implementation, is an element implemented in much the same way is; it does not have an end tag. However, for to have widespread use on the web, some facility for fallback content must be provided. Therefore, Mozilla's implementation requires an end tag ().

在Apple Safari里,的实现跟很相似,它并不没有结束标签。然而,为了使 能在web的世界里广泛适用,需要给替用内容提供一个容身之所,因此,在Mozilla的实现里结束标签()是必须的。

If fallback content is not needed, a simple will be fully compatible with both Safari and Mozilla -- Safari will simply ignore the end tag.

如果没有替用内容, 对 Safari 和 Mozilla 是完全兼容的—— Safari 会简单地忽略结束标签。

If fallback content is desired, some CSS tricks must be employed to mask the fallback content from Safari (which should render just the canvas), and also to mask the CSS tricks themselves from IE (which should render the fallback content).

如果有替用内容,那么可以用一些 CSS 技巧来为并且仅为 Safari 隐藏替用内容,因为那些替用内容是需要在 IE 里显示但不需要在 Safari 里显示。

渲染上下文(Rendering Context)

creates a fixed size drawing surface that exposes one or more rendering contexts, which are used to create and manipulate the content shown. We'll focus on the 2D rendering context, which is the only currently defined rendering context. In the future, other contexts may provide different types of rendering; for example, it is likely that a 3D context based on OpenGL ES will be added.

创建的固定尺寸的绘图画面开放了一个或多个渲染上下文(rendering context),我们可以通过它们来控制要显示的内容。我们专注于2D 渲染上,这也是目前唯一的选择,可能在将来会添加基于OpenGL ES 的 3D 上下文。

The is initially blank, and to display something a script first needs to access the rendering context and draw on it. The canvas element has a DOM method called getContext, used to obtain the rendering context and its drawing functions. getContext() takes one parameter, the type of context.

初始化是空白的,要在上面用脚本画图首先需要其渲染上下文(rendering context),它可以通过 canvas 元素对象的 getContext 方法来获取,同时得到的还有一些画图用的函数。getContext() 接受一个用于描述其类型的值作为参数。

var canvas = document.getElementById('tutorial');
var ctx = canvas.getContext('2d');
ログイン後にコピー

In the first line we retrieve the canvas DOM node using the getElementById method. We can then access the drawing context using the getContext method.

上面第一行通过 getElementById 方法取得 canvas 对象的 DOM 节点。然后通过其 getContext 方法取得其画图操作上下文。

检查浏览器的支持

The fallback content is displayed in browsers which do not support ; scripts can also check for support when they execute. This can easily be done by testing for the getContext method. Our code snippet from above becomes something like this:

除了在那些不支持 的浏览器上显示替用内容,还可以通过脚本的方式来检查浏览器是否支持 canvas 。方法很简单,判断 getContext 是否存在即可。

var canvas = document.getElementById('tutorial');
if (canvas.getContext){
  var ctx = canvas.getContext('2d');
  // drawing code here
} else {
  // canvas-unsupported code here
}
ログイン後にコピー

代码模板

Here is a minimalistic template, which we'll be using as a starting point for later examples. You can download this file to work with on your system.

我们会用下面这个最简化的代码模板来(后续的示例需要用到)作为开始,你可以 下载文件 到本地备用。


  
    Canvas tutorial
    
    
  
  
    <canvas id="tutorial" width="150" height="150"></canvas>
  

ログイン後にコピー

If you look at the script you'll see I've made a function called draw, which will get executed once the page finishes loading (via the onload attribute on the body tag). This function could also have been called from a setTimeout, setInterval, or any other event handler function just as long the page has been loaded first.

细心的你会发现我准备了一个名为 draw 的函数,它会在页面装载完毕之后执行一次(通过设置 body 标签的 onload 属性),它当然也可以在 setTimeout,setInterval,或者其他事件处理函数中被调用。

一个简单的例子

To start off, here's a simple example that draws two intersecting rectangles, one of which has alpha transparency. We'll explore how this works in more detail in later examples.

作为开始,来一个简单的吧——绘制两个交错的矩形,其中一个是有alpha透明效果。我们会在后面的示例中详细的让你了解它是如何运作的。

<html>
 <head>
  <script type="application/x-javascript">
    function draw() {
      var canvas = document.getElementById("canvas");
      if (canvas.getContext) {
        var ctx = canvas.getContext("2d");

        ctx.fillStyle = "rgb(200,0,0)";
        ctx.fillRect (10, 10, 55, 50);

        ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
        ctx.fillRect (30, 30, 55, 50);
      }
    }
  </script>
 </head>
 <body onload="draw();">
   <canvas id="canvas" width="150" height="150"></canvas>
 </body>
</html>
ログイン後にコピー
関連ラベル:
ソース:php.cn
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!