Canvas标签
H5新标签Canvas对象封装了很多绘图功能, 使用JavaScript绘制.
Canvas绘图流程:
绘制内容显示Canvas画布里
<canvas id="canvas"></canvas> /*画布*/
使用Canvas内置对象context来画图
var canvas = document.getElementById("canvas"); // 获取画布 var ctx = canvas.getContext("2d"); //获取画布的对象 // 使用js操作ctx对象来绘制图像
绘制矩形
- 绘图有两种基本方式:空心描边
Strike
, 实心填充Fill
。var canvas = document.getElementById("myCanvas"); var context = canvas.getContext('2d'); // 绘制一个空心矩形,左上角是(0,0)宽度是200px,高度是100px。 context.strokeRect(0, 0, 200, 100); // 绘制一个实心矩形 context.fillRect(0, 150, 200, 100);
Canvas样式
context.fillStyle = "purple"; // 填充颜色
context.strokeStyle = "green"; // 描边颜色
context.lineWidth = 2; // 线的宽度
案例
像素图
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
window.onload = function(){
var cvs = document.getElementById("cvs")
var context = cvs.getContext("2d");
var size = 20;
var matrx = [
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
];
for(var y=0; y<matrx.length; y++){
for(var x=0; x<matrx[y].length; x++){
if(matrx[y][x] == 1){
context.fillRect(x*size, y*size, size, size);
} else {
context.strokeRect(x*size, y*size, size, size);
}
}
}
};
</script>
</head>
<body>
<canvas id="cvs" width="500" height="300">您的浏览器不支持Canvas。</canvas>
</body>
</html>