Maison  >  Article  >  interface Web  >  HTML5 canvas画布详解(一)

HTML5 canvas画布详解(一)

黄舟
黄舟original
2017-03-17 15:32:423062parcourir

HTML5canvas元素用于在网页上绘制图形。

Canvas的特点

  • Canvas画布是一个矩形区域,可以控制其每一个像素

  • Canvas使用JavaScript来控制画图

  • Canvas具有直线、矩形、圆以及添加图像的方法

Canvas标签的使用

下面的代码是使用canvas画面绘制一个200*200红色矩形:

<!Doctype html>
<html>
<head>
<title>我的canvas页面</title>
<meta charset="utf-8"/>
</head>
<body>
<canvas id="myCanvas" width="200" height="200">
</canvas>
<script type="text/javascript">
    var c=document.getElementById("myCanvas");    var cxt=c.getContext("2d");
    cxt.fillStyle="#FF0000";
    cxt.fillRect(0,0,200,200);
    </script>
    </body>
    </html>

将上面的代码保存为canvas.html,并将其编码设置为utf-8(否则中文乱码),使用浏览器打开就可以看到如下效果:
canvsf运行效果

<canvas id="myCanvas" width="200" height="200">

这里创建Canvas标签,并定义其id为myCanvas,便于JavaScript绘图时获取该标签对象
再看JavaScript绘图部分:

    var c=document.getElementById("myCanvas");
    var cxt=c.getContext("2d");
    cxt.fillStyle="#FF0000";
    cxt.fillRect(0,0,200,200);

第一句getElementById,通过Canvas标签的ID获取canvas对象。
第二句getContext,获取context对象。
第三句调用Context对象的方法fillStyle,即填充其颜色。
第四句调用Context对象的fillRect方法指定填充的区域。

Canvas的其他实例

直线

我的canvas页面



<canvas id="myCanvas" width="200" height="200">

运行结果如下:
这里写图片描述




我的canvas页面



<canvas id="myCanvas" width="200" height="200">

运行结果如下:
这里写图片描述

渐变

我的canvas页面



<canvas id="myCanvas" width="200" height="200">


    
    

效果如下:
这里写图片描述

图像

<!Doctype html>
<html>
<head>
<title>我的canvas页面</title>
<meta charset="utf-8"/>
</head>
<body>
<canvas id="myCanvas" width="800" height="600">
</canvas>
<script type="text/javascript">
    var c=document.getElementById("myCanvas");    
    var cxt=c.getContext("2d");    
    var img=new Image();
    img.src="1.png";
    img.onload=function(e){
        cxt.drawImage(img,0,0);
    }
    cxt.drawImage(img,0,0);
    </script>
    </body>
    </html>

注意,一定要给Img添加onload事件,否则图片不显示。
其中,1.png为自己找的图片素材。打开页面可以看到图片显示在canvas画布中了。我的运行效果如下,图片百度随便找的,凑合看~~
这里写图片描述

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn