HTML5 Canvas 标签的使用
js用Canvas绘制图形:
var CANVAS_WIDHT=500,CANVAS_HEIGHT=500;
var mycanvas,context;
window.onload=function(){
createCanvas();
drawRect()
}
function createCanvas(){
document.body.innerHTML="<canvas id=\"mycanvas\"width=\""+CANVAS_WIDHT+"\"height=\""+CANVAS_HEIGHT+"\"></canvas>"
mycanvas=document.getElementById("mycanvas");
context=mycanvas.getContext("2d");
}
function drawRect(){
context.fillStyle="#ff0000";
context.rotate(45);
context.fillRect(0,0,200,200);
}
绘制圆形
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script>
function draw(id){
var canvas=document.getElementById(id);
if(canvas==null){
return false;
}
var context=canvas.getContext("2d");//指定绘制2d图型;
context.fillStyle="#eeeeef";//绘制的颜色
context.fillRect(0,0,600,700);//绘制一个矩形
for(var i=0;i<=10;i++){
context.beginPath();//绘制路径
context.arc(i*25,i*25,i*10,0,Math.PI*2,true);//绘制圆型
context.closePath();//关闭绘制路径
context.fillStyle="rgba(255,0,0,0.25)";
context.fill();//绘制成功
}
}
</script>
</head>
<body onload="draw('canvas')">
<canvas id="canvas" width="600px" height="700px"></canvas>
</body>
</html>
绘制渐变颜色:
<script>
function draw(id){
var canvas=document.getElementById(id);
var context=canvas.getContext("2d");
var g1=context.createLinearGradient(0,0,0,300);
g1.addColorStop(0,"rgb(255,255,0)");
g1.addColorStop(1,"rgb(0,255,255)");
context.fillStyle=g1;
context.fillRect(0,0,500,500);
}
</script>
</head>
<body onload="draw('canvas')">
<canvas id="canvas" width="300px" height="400px"></canvas>
</body>
图型重叠效果:
<script>
function draw(id){
var canvas=document.getElementById(id);
var context=canvas.getContext("2d");
var oprtns=new Array(
"source-atop",
"source-in",
"source-out",
"source-over",
"destination-atop",
"destination-in",
"destination-out",
"destination-over",
"lighter",
"copy",
"xor");
i=1;
context.fillStyle="blue";
context.fillRect(10,10,60,60);
context.globalCompositeOperation=oprtns[i];
context.beginPath();
context.fillStyle="red";
context.arc(60,60,30,MathPI*2,false);
context.fill();
}
</script>
</head>
<body onload="draw('canvas')">
<canvas id="canvas" width="300px" height="400px"></canvas>
</body>
图片绘制:
<script>
function draw(id){
var canvas=document.getElementById(id);
var context=canvas.getContext("2d");
context.fillStyle="blue";
context.fillRect(0,0,500,500);
image=new Image();
image.src="tupian.png";
image.onload=function(){
drawImage(context,image);
}
}
function drawImage(context,image){
context.drawImage(image,0,0,200,200);
}
</script>
</head>
<body onload="draw('canvas')">
<canvas id="canvas" width="300px" height="400px"></canvas>
</body>
</html>