用canvas绘制一个蓝色矩形,显示在网页上
DrawRectangle.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Draw a blue rectangle</title>
</head>
<body onload="main()">
<canvas id="example" width="400" height="400">
Please use a browser that supports "canvas"
</canvas>
<script src="DrawRectangle.js"></script>
</body>
</html>
main()作为JS程序的入口,在下面的JS中实现
DrawRectangle.js:
function main(){
var canvas = document.getElementById("example");
if(!canvas){
console.log("Failed to retrieve the <canvas> element");
return false;
}
//Get the rendering context for 2DCG
var ctx = canvas.getContext("2d");
ctx.fillStyle = '#0000ff'; //设置填充颜色为蓝色 用'rgba(0,0,255,1.0)'也可
ctx.fillRect(120,10,150,150); //填充矩形
}
canvas不直接提供绘图的方法,而是提供叫上下文(context)的机制进行绘图。
canvas.getContext(“2d”)指定上下文类型为二维,来绘制二维图形。同理:3d就是三维图形。