js使用canvas绘制米字格完整代码

米字格在练字初期有着及其重要的作用,合理的利用米字格可以有效的帮助我们练好字.

本文介绍js基于canvas如何绘制米字格效果,效果如下:


从上图可知,米字格由4条实线和4条虚线组成,那么也就意味着在绘制中就是对实线和虚线的处理.

如果需要查看田字格画法,可本站搜索"使用js在canvas中绘制田字格完整代码"

完整代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
#div1 {
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<div id="div1">
<canvas width="100" height="100" id="cs">你的浏览器不支持canvas!</canvas>
</div>
<script type="text/javascript">
var oCanvas = document.getElementById('cs');
if (oCanvas.getContext) {
var ctx = oCanvas.getContext('2d'),
w = oCanvas.width,
half = w / 2; //每条虚线的实线部分长度为5
ctx.strokeStyle = '#FF0000';
ctx.lineWidth = 2;
ctx.strokeRect(1, 1, w - 2, w - 2);
drawSimpleUnreal(ctx);
}
function drawSimpleUnreal(ctx){
ctx.save();
ctx.lineWidth = 1;
ctx.beginPath();
ctx.setLineDash([5,5]); //创建5像素长,间隔为5像素的虚线
//横线
ctx.moveTo(0, half);
ctx.lineTo(w, half);
//竖线
ctx.moveTo(half, 0);
ctx.lineTo(half, w);
//交叉线1
ctx.moveTo(0, 0);
ctx.lineTo(w, w);
//交叉线2
ctx.moveTo(0, w);
ctx.lineTo(w, 0);
ctx.stroke();
ctx.closePath();
ctx.restore();
}
</script>
</body>
</html>

运行以上代码,即可得到如图效果.

六月初字帖坊小程序 你想要的字帖模板及工具,这里都有!