今天教大家绘制简单的图形(代码如下:)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>HTML5 移动Web开发指南</title>
<style type="text/css">
h1, h5
{
text-align: center;
}
canvas
{
float: left;
margin: 10px;
overflow: hidden;
}
</style>
<script type="text/javascript" language="javascript">
window.onload = function () {
drawCanvas(0, 0, "canvase_01", "red", 200, 200);
drawCanvas(0, 0, "canvase_02", "green", 200, 100);
drawCanvas(0, 0, "canvase_05", "blank", 300, 60);
drawCanvas(75, 60, "canvase_05", "gray", 150, 90);
drawCanvas(0, 0, "canvase_06", "blank", 300, 50);
drawCanvas(0, 50, "canvase_06", "red", 300, 50);
drawCanvas(0, 100, "canvase_06", "#F8CB1C", 300, 50);
drawCanvas(0, 0, "canvase_07", "green", 100, 150);
drawCanvas(100, 0, "canvase_07", "white", 100, 150);
drawCanvas(200, 0, "canvase_07", "red", 100, 150);
drawRound("canvase_03", "blue", 75, true);
drawRound("canvase_04", "yellow", 75, false);
drawRound("canvase_08", "red", 75, true);
drawRound("canvase_08", "yellow", 75, false);
};
/*
* Canvas 画非圆图形测试
* x: 图形的X轴开始坐标
* y: 图形的Y轴开始坐标
* id: 元素id
* bgColor: 填充的背景颜色
* 宽
* height: 高
*/
function drawCanvas(x, y, id, bgColor, width, height) {
var canvas = document.getElementById(id);
if (canvas != null && canvas != undefined) {
var ctx = canvas.getContext("2d");
ctx.fillStyle = bgColor;
//第一个和第二个参数,代表开始坐标
//第三个参数是图形的宽
//第四个参数是图形的高
ctx.fillRect(Number(x), Number(y), Number(width), Number(height));
}
}
/*
* Canvas 画圆测试
* id: 元素id
* bgColor: 填充的背景颜色
* R: 圆半径
* IsRound: 是否为正圆(true正圆、false 半圆)
*/
function drawRound(id, bgColor, R, IsRound) {
var canvas = document.getElementById(id);
if (canvas != null && canvas != undefined) {
var ctx = canvas.getContext("2d");
ctx.fillStyle = bgColor;
ctx.beginPath();
var round = Math.PI;
if (Boolean(IsRound))
round = Math.PI * 2;
//第一个和第二个参数,代表圆心坐标
//第三个参数是圆的半径
//第四个参数代表圆周起始位置(0 起始位置。沿顺时针路线,分别是0.5 (正下方),1 PI和1.5 PI(正上方),为画饼图提供了扇形范围的依据)
//第五个参数是弧长(Math.PI*1 半圆、Math.PI*2就是整个圆)
ctx.arc(150, 75, Number(R), 0, round, true);
ctx.closePath();
ctx.fill();
}
}
</script>
</head>
<body>
<header>
<section>
<h1>
HTML5 移动Web开发指南</h1>
</section>
</header>
<fieldset>
<legend>HTML5 新元素--Canvas绘图元素</legend>
<article>
<section>
<canvas id="canvase_01">
您的浏览器不支持Canvas元素!
</canvas>
<canvas id="canvase_02">
您的浏览器不支持Canvas元素!
</canvas>
<canvas id="canvase_03">
您的浏览器不支持Canvas元素!
</canvas>
<canvas id="canvase_04">
您的浏览器不支持Canvas元素!
</canvas>
<canvas id="canvase_05">
您的浏览器不支持Canvas元素!
</canvas>
<canvas id="canvase_06">
您的浏览器不支持Canvas元素!
</canvas>
<canvas id="canvase_07">
您的浏览器不支持Canvas元素!
</canvas>
<canvas id="canvase_08">
您的浏览器不支持Canvas元素!
</canvas>
</section>
</article>
</fieldset>
<footer>
<section>
<h5>
<span style="font-family: Arial, Helvetica, sans-serif;">HTML5 新元素--Canvas绘图元素</span>
</h5>
</section>
</footer>
</body>
</html>
以上就是见单的一些canvas画布图形,完成后的运行结果如下: