>  기사  >  웹 프론트엔드  >  HTML5 Canvas 개요_html5 튜토리얼 팁

HTML5 Canvas 개요_html5 튜토리얼 팁

WBOY
WBOY원래의
2016-05-16 15:51:211377검색

5ba626b379994d53f7acf72a64f9b697는 스크립트 언어(일반적으로 JavaScript)를 사용하여 그래픽을 그리는 데 사용할 수 있는 새로운 HTML 요소입니다. 예를 들어, 그림을 그리거나 이미지를 합성하거나 간단한(그리 단순하지는 않은) 애니메이션을 만드는 데 사용할 수 있습니다. 오른쪽 이미지는 이 튜토리얼 전체에서 볼 수 있는 50deac90c8f74b69391c9996b22bd408 구현의 몇 가지 예를 보여줍니다.

5ba626b379994d53f7acf72a64f9b697는 Apple의 Mac OS X Dashboard에서 처음 소개된 후 Safari에서 사용되었습니다. Firefox 1.5와 같은 Gecko 1.8 기반 브라우저도 이 새로운 요소를 지원합니다. 5ba626b379994d53f7acf72a64f9b697 요소는 HTML 5 표준 사양이라고도 알려진 WhatWG 웹 애플리케이션 1.0의 일부입니다.

이 튜토리얼에서는 웹페이지에서 5ba626b379994d53f7acf72a64f9b697 요소를 사용하는 방법을 설명하겠습니다. 제공된 예는 50deac90c8f74b69391c9996b22bd408로 무엇을 할 수 있는지에 대한 명확한 아이디어를 제공합니다. 이러한 예는 50deac90c8f74b69391c9996b22bd408를 적용하기 위한 출발점이 될 수도 있습니다.

시작하기 전에
HTML과 JavaScript에 대한 기본 지식이 있다면 요소를 사용하는 것은 어렵지 않습니다.

위에서 언급했듯이 모든 최신 브라우저가 5ba626b379994d53f7acf72a64f9b697 요소를 지원하는 것은 아니므로 모든 예제 작업을 보려면 Firefox 1.5 이상, Opera 9와 같은 다른 Gecko 기반 브라우저 또는 최신 버전의 Safari가 필요합니다.

50deac90c8f74b69391c9996b22bd408 요소

5ba626b379994d53f7acf72a64f9b697 요소 자체를 살펴보는 것으로 이 튜토리얼을 시작하겠습니다.
5ba626b379994d53f7acf72a64f9b697 요소의 정의부터 시작하겠습니다.

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

a1f02c36ba31691bcfe87b2722de723b 요소와 매우 비슷해 보이지만 유일한 차이점은 srcalt 속성이 없다는 점입니다. ;canvas>는 a1f02c36ba31691bcfe87b2722de723b와 매우 유사해 보이지만 유일한 차이점은 srcalt 속성이 포함되어 있지 않다는 것입니다. 5ba626b379994d53f7acf72a64f9b697 요소에는 widthheight라는 두 가지 속성만 있습니다. 둘 다 선택 사항이며 DOM 속성이나 CSS 규칙을 사용하여 설정할 수도 있습니다. widthheight 두 가지 속성만 있으며 둘 다 선택 사항이며 DOM 또는 CSS를 사용하여 설정할 수 있습니다. 너비 및 높이 속성이 지정되지 않은 경우 캔버스는 처음에 너비가 300픽셀이고 높이가 150픽셀입니다. 너비 및 높이 속성이 지정되지 않은 경우 기본값은 300입니다. 가로 , 세로 150픽셀 . 요소의 크기는 CSS에 의해 임의로 조정될 수 있지만 렌더링하는 동안 이미지의 크기는 레이아웃 크기에 맞게 조정됩니다. (렌더링이 왜곡된 것처럼 보이는 경우 5ba626b379994d53f7acf72a64f9b697 속성에서 너비 및 높이 속성을 명시적으로 지정해 보세요. , CSS로는 불가능합니다.) CSS를 통해 캔버스의 크기를 조정할 수 있지만 렌더링된 이미지는 레이아웃에 맞게 크기가 조정됩니다. (렌더링 결과가 변형된 것처럼 보인다면 CSS에만 의존할 필요는 없습니다.) . 캔버스의 너비와 높이 속성 값을 명시적으로 지정할 수 있습니다.

id 속성은 5ba626b379994d53f7acf72a64f9b697 요소에만 국한되지 않지만 거의 모든 HTML 요소(예: )에 적용할 수 있는 기본 HTML 속성 중 하나입니다. 🎜>class 예) 항상 ID를 제공하는 것이 좋습니다. 이렇게 하면 스크립트에서 식별하기가 훨씬 쉬워집니다.
id 속성은 < canvas> ; 표준 HTML 태그와 마찬가지로 모든 HTML 요소는 id 값을 지정할 수 있습니다. 일반적으로 요소에 id를 할당하는 것이 좋습니다. 이렇게 하면 스크립트에서 해당 요소를 더 쉽게 사용할 수 있습니다.

5ba626b379994d53f7acf72a64f9b697 요소는 일반 이미지(여백, 테두리, 배경 등)와 마찬가지로 스타일을 지정할 수 있지만 이러한 규칙은 캔버스의 실제 그림에는 영향을 미치지 않습니다. 이 튜토리얼의 뒷부분에서 캔버스에 스타일 지정 규칙이 적용되지 않으면 처음에는 완전히 투명하게 됩니다. 5ba626b379994d53f7acf72a64f9b697 요소는 일반 이미지(여백, 테두리, 배경 등). 그러나 이러한 스타일은 캔버스에서 생성된 실제 이미지에 아무런 영향을 미치지 않습니다. 다음으로 스타일을 적용하는 방법을 살펴보겠습니다. 스타일을 지정하지 않으면 캔버스는 기본적으로 완전히 투명합니다.

대체 콘텐츠

5ba626b379994d53f7acf72a64f9b697 요소는 아직 비교적 새로운 요소이고 일부 브라우저(예: Firefox 1.0 및 Internet Explorer)에서는 구현되지 않기 때문에 브라우저가 지원하지 않는 경우 대체 콘텐츠를 제공하는 수단이 필요합니다. 해당 요소를 지원하지 않습니다.

因为 5ba626b379994d53f7acf72a64f9b697 相对较新,有些浏览器并没实现,如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>

结束标签 c2caaf3fc160dd2513ce82f021917f8b 是必须的

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

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

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

如果没有替用内容,65ec36afffd8edae2a5cf0c4e555c057c2caaf3fc160dd2513ce82f021917f8b 对 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)

5ba626b379994d53f7acf72a64f9b697 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.

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

The 5ba626b379994d53f7acf72a64f9b697 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.

5ba626b379994d53f7acf72a64f9b697 初始化是空白的,要在上面用脚本画图首先需要其渲染上下文(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 5ba626b379994d53f7acf72a64f9b697; 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>
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.