canvas 实现网格
2d游戏中经常用到网格,点击的时候会有一个新的物体放上去很简单 网线是画直线 每个多宽画一条,同样画竖线也是这样,最关键的是确定鼠标在哪个方格中,也很简单鼠标位置处以方格的宽度,就得的整数就是横向的方格位置,竖向同理可得,附上源码
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="lib/canvas/canvas-1.2.dev.js">
</script>
<title>测试Canvas 方法</title>
</head>
<body style="padding:0 0 0 0; margin:0 0 0 0;">
<div style="width:100%;height:100%; padding:0 0 0 0; margin:0 0 0 0; font-size:50px;">
<canvas style="background-color:#ffffff; width:100%; height:100%; padding:0 0 0 0; margin:0 0 0 0;" id="ctMs">
</canvas>
</div>
<script type="text/javascript">
var cvs = Canvas("ctMs", 0);
var i = 0;
cvs.clear();
cvs.fillStyle('rgba(0, 0, 255, 0.5)');
cvs.fillRect(150, 100, 100, 50); // ALIGN.LEFT.TOP is the default alignment
cvs.strokeStyle('#333333');
cvs.grid(40, 50);
var positionLayer = cvs.createLayer('position', 0);
positionLayer.onMouseMove = function(x, y){
// clear the canvas and set stroke color to red
this.clear();
this.strokeColor('#FF0000');
// stroke a crossing at mouse coordinates
this.strokeLine(x, 0, x, this.height);
this.strokeLine(0, y, this.width, y);
// display the coordinates as text also
this.fillColor('#FF0000');
this.font('12px Arial');
var currentPos = getCurrentPos(x, y, 40, 50);
this.fillText(currentPos.xs + 'x' + currentPos.ys, x - 4, y + 4, ALIGN.RIGHT.TOP);
this.save();
this.fillStyle('rgba(0, 0, 255, 0.5)');
this.translate(currentPos.xs * 40, currentPos.ys * 50);
this.fillRect(0, 0, 40, 50);
this.restore();
this.renderSingleFrame();
}
cvs.onMouseDown = function(x, y, button){
var currentPos = getCurrentPos(x, y, 40, 50);
var positionLayer = cvs.createLayer('position' + (i++), 0, function(){
this.save();
this.fillStyle('rgba(0, 0, 255, 0.5)');
this.translate(currentPos.xs * 40, currentPos.ys * 50);
this.fillRect(0, 0, 40, 50);
this.restore();
});
}
function getCurrentPos(x, y, xStop, yStop){
var xPos = ~ ~ (x / xStop);
var yPos = ~ ~ (y / yStop)
return {
xs: xPos,
ys: yPos
};
}
</script>
</body>
</html>
截图效果
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架