Maison > interface Web > tutoriel HTML > le corps du texte

html5 canvas模拟实现树的生长_html/css_WEB-ITnose

WBOY
Libérer: 2016-06-21 08:46:38
original
1491 Les gens l'ont consulté

h5+css3

html5+css3一直是web开发的热点,作为一个PHP工程师的我也很喜欢这个领域,自1999年以后HTML 4.01 已经改变了很多,今天,在HTML 4.01中的几个已经被废弃,这些元素在HTML5中已经被删除或重新定义。为了更好地处理今天的互联网应用,HTML5添加了很多新元素及功能,比如: 图形的绘制,多媒体内容,更好的页面结构,更好的形式 处理,和几个api拖放元素,定位,包括网页 应用程序缓存,存储,网络工作者等。

canvas介绍

canvas是我们这篇文章的主角

标签 描述
标签定义图形,比如图表和其他图像。该标签基于 JavaScript 的绘图 API

具体的html5用法可以参照这个手册慢慢研究,我也是刚刚开始关注这个领域发现很有用,在图像的处理上堪称完美html5教程

简单实践

学了就像做出点什么,模拟个树的生长这是效果截图

先上代码

<!doctype html><html lang="en"><head>    <meta charset="UTF-8">    <title>tree</title></head><body>    <canvas id='d1' width="600" height="500" style="border:dashed 2px #ccc;"></canvas>    <script>    var drawtree = function (ctx,startx,starty,length,angle,depth,branchWidth){        var rand=Math.random,        n_length,n_angle,n_depth,maxbranch=4,        endx,endy,maxangle=2 * Math.PI / 4;        var subbranch;        ctx.beginPath();        ctx.moveTo(startx,starty);        endx=startx + length * Math.cos(angle);        endy=starty + length * Math.sin(angle);        ctx.lineCap='round';        ctx.lineWidth=branchWidth;        ctx.lineTo(endx,endy);        if(depth<=2 ){            //树的枝干            ctx.strokeStyle= 'rgb(0,' + (((rand() * 64) +128) >>0) + ',0)';        }        else{            //树的叶子            ctx.strokeStyle= 'rgb(0,' + (((rand() * 64) +64) >>0) + ',50,25)';        }        ctx.stroke();        n_depth = depth-1;        //判断树是否结束        if(!n_depth){            return;        }        subbranch= (rand() * (maxbranch-1)) + 1;        branchWidth *=0.5;         for(var i=0;i<subbranch;i++){            n_angle = angle +rand() * maxangle -maxangle *0.5;            n_length = length * (0.5 + rand() *0.5);            setTimeout(function (){                drawtree(ctx,endx,endy,n_length,n_angle,n_depth,branchWidth);                return;            },500)        }    }    var canvas=document.getElementById('d1');    var ctx= canvas.getContext('2d');    //初始化的树    drawtree(ctx,300,470,100,-Math.PI / 2, 12, 12);    </script></body></html>
Copier après la connexion

效果还不错吧,但代码并不长,就喜欢这种东西,哈哈哈~基本想法就是用黑色的line来模拟树枝,绿色的line来模拟树叶,然后使用setTimeout来产生个动画,每画出一条就以这个为起点来生成其他的分支,直到深度达到设定值停止。

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
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
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!