📜  HTML5-画布

📅  最后修改于: 2020-10-23 06:17:12             🧑  作者: Mango


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

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


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

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

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


   
   
   
      
   

这将产生以下结果-

渲染上下文

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

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

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

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-


HTML5画布示例

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

Sr.No. Examples & Description
1 Drawing Rectangles

Learn how to draw rectangle using HTML5 element

2 Drawing Paths

Learn how to make shapes using paths in HTML5 element

3 Drawing Lines

Learn how to draw lines using HTML5 element

4 Drawing Bezier

Learn how to draw Bezier curve using HTML5 element

5 Drawing Quadratic

Learn how to draw quadratic curve using HTML5 element

6 Using Images

Learn how to use images with HTML5 element

7 Create Gradients

Learn how to create gradients using HTML5 element

8 Styles and Colors

Learn how to apply styles and colors using HTML5 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.