仅仅只是一个简单的hello world.
js代码很简单:
- <!DOCTYPE HTML>
- <html lang="cn">
- <head>
- <title> canvas1 </title>
- <meta charset="UTF-8">
- //@author 杨虹昌
- <script type="text/javascript">
- //测试浏览器是否支持canvas
- function canvasSupport(){
- return !!document.createElement('canvas').getContext;
- }
- //添加window事件,文档加载完成之后执行此函数
- window.addEventListener('load',eventWindowLoaded,false);
- //输出日志信息对象简单封装
- var Debugger=function(){};
- Debugger.log=function(message){
- try{
- console.log(message);
- }catch(e){
- return;
- }
- }
- //窗体加载后执行函数
- function eventWindowLoaded(){
- canvasApp();
- }
- //
- function canvasApp(){
- if(!canvasSupport()){
- return;
- }
- //获取html元素id为theCanvas的画布元素
- var theCanvas=document.getElementById('theCanvas');
- //获得2D上下文,注意:此处2d只能是小写,大写则为undefined,很郁闷为何不做静态常量,也许是我不知道吧
- var context=theCanvas.getContext('2d');
- //输出信息
- Debugger.log('Drawing Canvas');
- //画对应类容
- function drawScreen(){
- //background 设置背景颜色
- context.fillStyle="#ffffaa";
- context.fillRect(0,0,500,300);
- //font 设置字体
- context.fillStyle="#000000";
- context.font="20px_sans";
- context.textBaseline="top";
- context.fillText("Hello World",195,80);
- //image 加载一张图片并输出到画布
- var helloWorldImage=new Image();
- helloWorldImage.src="http://avatar.csdn.net/0/E/9/1_yhc13429826359.jpg";
- helloWorldImage.onload=function(){
- context.drawImage(helloWorldImage,160,130);
- };
- //border 边框设置
- context.strokeStyle="#000000";
- context.strokeRect(5,5,490,290);
- }
- drawScreen();
- }
- </script>
- </head>
- <body>
- <div style="position:absolute;top:50px;left:50px;">
- <canvas id="theCanvas" width="500" height="500">
- 浏览器不支持html5 canvas,建议使用chrome,FF
- </canvas>
- </body>
- </html>
最终效果图:
只是一个最简单的例子,后续会详细解释.