HTML5 Canvas 初探
js代码很简单:
[javascript]
<!doctype html>
<html lang="cn">
<head>
<title> canvas1 </title>
<meta charset="utf-8">
[javascript]
//@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=/uploadfile/2013/1028/20131028034833472.jpg";
helloworldimage.onload=function(){
context.drawimage(helloworldimage,160,130);
};
//border 边框设置
context.strokestyle="#000000";
context.strokerect(5,5,490,290);
}
drawscreen();
}
</script>
</head>
<body>
<p style="position:absolute;top:50px;left:50px;">
<canvas id="thecanvas" width="500" height="500">
浏览器不支持html5 canvas,建议使用chrome,ff
</canvas>
</body>
</html>
最终效果图: