|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
代码中没有涉及到过多的变量读写,程序执行过程中变量的值正常,任务管理器cpu,内存占用正常,但是电脑就是会变卡, 检查了多遍就是不解, 求解决!!!!
- // 全局属性
- var c = null,
- ctx = null,
- // 地图
- map = null,
- // 黑棋、白棋,黑棋预落子,白棋预落子
- blackPiece = null,
- whitePiece = null,
- blackPieceA = null,
- whitePieceA = null,
- // 格子,棋子的大小
- size = null,
- // size的一半
- halfSize = null,
- // 画线的数量
- number = null,
- // 鼠标所在的X,Y坐标
- // mapX = null,
- // mapY = null,
- // 频繁读取的坐标变量
- x = null,
- y = null,
- // 游戏帧率
- fps = null;
- window.onload = function () {
- c = document.getElementById("myCanvas");
- ctx = c.getContext("2d");
- ctx.strokeStyle = "#444041";
- fps = 1000 / 10;
- size = 50;
- halfSize = size / 2;
- number = 16;
- // mapX = halfSize;
- // mapY = halfSize;
- blackPiece = document.createElement('img');
- blackPiece.src = "./imgs/black.png";
- whitePiece = document.createElement('img');
- whitePiece.src = "./imgs/white.png";
- blackPieceA = document.createElement('img');
- blackPieceA.src = "./imgs/_black.png";
- whitePieceA = document.createElement('img');
- whitePieceA.src = "./imgs/_white.png";
- // 地图的初始化, 1-黑棋, 2-白棋, 0-无子
- initMap();
- console.log(map);
- // 游戏开始
- begin();
- };
- function initMap() {
- map = [];
- for (let x = 0; x < number; x++) {
- map[x] = [];
- for (let y = 0; y < number; y++) {
- map[x][y] = 0;
- }
- }
- }
- function drawCheckerboard() {
- // 准备重绘棋盘
- ctx.clearRect(0, 0, c.width, c.height);
- // 画棋盘线条
- for(let x = 0; x < number; x++) {
- ctx.moveTo((x + 1) * size, size);
- ctx.lineTo((x + 1) * size, number * size);
- }
- for(let y = 0; y < number; y++) {
- ctx.moveTo(size, (y + 1) * size);
- ctx.lineTo(number * size, (y + 1) * size);
- }
- ctx.stroke();
- // 绘制棋盘上的棋子
- for (let x = 0; x < number; x++) {
- for (let y = 0; y < number; y++) {
- if(1 == map[x][y]) {
- ctx.drawImage(blackPiece, (x + 0.5) * size, (y + 0.5) * size, size, size);
- }
- else if(2 == map[x][y]) {
- ctx.drawImage(whitePiece, (x + 0.5) * size, (y + 0.5) * size, size, size);
- }
- }
- }
- }
- function drawPos() {
- // 判断鼠标是否在棋盘
- if(x < halfSize || y < halfSize ||
- x > c.width - halfSize || y > c.height - halfSize) {
- return;
- }
- console.log("mapX: ", mapX, " mapY:", mapY)
- console.log(" x: ", x, " y: ", y);
- ctx.drawImage(whitePieceA, x, y, size, size);
- }
- function begin() {
- window.setInterval(
- // 获取当前坐标
- function () {
- c.onmousemove = function (e) {
- // 如果此时落子,则落在(x,y)处, 圆心为(x+halfSize, y+halfSize)
- x = Math.floor((e.layerX + halfSize) / size) * size - halfSize;
- y = Math.floor((e.layerY + halfSize) / size) * size - halfSize;
- return;
- }
- drawCheckerboard();
- drawPos();
- },
- fps
- );
- }
复制代码
上面是代码, 下面有压缩包,感谢解答!!! |
|