Categories
HTML教程

HTML5-画布

HTML5-画布


HTML5元素<canvas>为您提供了一种使用JavaScript绘制图形的简单有效的方法。它可以用来绘制图形,制作照片或做简单(而不是那么简单)的动画。

这是一个简单的<canvas>元素,它只有两个特定的属性widthheight以及所有核心HTML5属性,例如id,name和class等。

<canvas id="mycanvas" width="100" height="100"></canvas>

您可以使用getElementById()方法轻松地在DOM中找到<canvas>元素,如下所示-

var canvas = document.getElementById("mycanvas");

让我们看一个在HTML5文档中使用<canvas>元素的简单示例。

<style>
         #mycanvas{border:1px solid red;}
      </style>
   
   
   
      <canvas id="mycanvas" width="100" height="100"></canvas>
   

这将产生以下结果-

渲染上下文

<canvas>最初是空白的,并且要显示某些内容,脚本首先需要访问渲染上下文并在其上进行绘制。

canvas元素具有一个称为getContext的DOM方法,该方法用于获取渲染上下文及其绘图功能。此函数采用一个参数,即上下文2d的类型。

以下是获取所需上下文的代码,以及检查您的浏览器是否支持<canvas>元素-

var canvas  = document.getElementById("mycanvas");

if (canvas.getContext) {   
   var ctx = canvas.getContext('2d');   
   // drawing code here   
} else {   
   
   // canvas-unsupported code here 
}  

浏览器支持

Firefox,Safari,Chrome和Opera的最新版本均支持HTML5 Canvas,但IE8本身不支持canvas。

您可以使用ExplorerCanvas通过Internet Explorer获得画布支持。您只需要按如下方式包含此JavaScript-

<!--[if IE]><script src = "excanvas.js"></script><![endif]-->

HTML5画布示例

本教程介绍了以下与HTML5 <canvas>元素相关的示例。

Sr.No. Examples & Description
1 Drawing Rectangles

Learn how to draw rectangle using HTML5 <canvas> element

2 Drawing Paths

Learn how to make shapes using paths in HTML5 <canvas> element

3 Drawing Lines

Learn how to draw lines using HTML5 <canvas> element

4 Drawing Bezier

Learn how to draw Bezier curve using HTML5 <canvas> element

5 Drawing Quadratic

Learn how to draw quadratic curve using HTML5 <canvas> element

6 Using Images

Learn how to use images with HTML5 <canvas> element

7 Create Gradients

Learn how to create gradients using HTML5 <canvas> element

8 Styles and Colors

Learn how to apply styles and colors using HTML5 <canvas> element

9 Text and Fonts

Learn how to draw amazing text using different fonts and their size.

10 Pattern and Shadow

Learn how to draw different patterns and drop shadows.

11 Canvas States

Learn how to save and restore canvas states while doing complex drawings on a canvas.

12 Canvas Translation

This method is used to move the canvas and its origin to a different point in the grid.

13 Canvas Rotation

This method is used to rotate the canvas around the current origin.

14 Canvas Scaling

This method is used to increase or decrease the units in a canvas grid.

15 Canvas Transform

These methods allow modifications directly to the transformation matrix.

16 Canvas Composition

This method is used to mask off certain areas or clear sections from the canvas.

17 Canvas Animation

Learn how to create basic animation using HTML5 canvas and JavaScript.

error: 内容受到保护 !!