我用 JavaScript、Canvas 和 Bootstrap Design 创建了一个小游戏。
您可以看到以下面板(请注意,该面板在 Firefox 和 Chrome 上是清晰的,即没有模糊的交叉线和圆圈):
一切看起来都很好,除了当我缩放以检查黑色和白色碎片是否很好地居中到每个案例中时,这里是缩放:
如您所见,圆圈没有居中,即在左侧水平移动,在顶部垂直移动。
但是,我在“width_board + 0.5”和“height_board + 0.5”像素上绘制了每条交叉线,以获得清晰的板。
为了执行此操作,我已经完成了有关 CSS 的工作:
#game-wrapper {
border: 5px solid black;
cursor: crosshair;
margin: 0;
float: left;
width: 481px;
height: 481px;
/* Rounded corners */
overflow: hidden;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
border-radius: 10px 10px 10px 10px;
}
并进入 HTML 页面:
<div id="game-wrapper">
<canvas id="game-canvas" width="480" height="480"></canvas>
</div>
圆圈位于:
var canvas = document.getElementById('game-canvas');
// Size of canvas
var width = canvas.width,
height = canvas.height;
// Radius of each piece
var radius = 0.9 * width/16;
// Drawing main frame
for (i = 0; i < 8; i++)
for (j = 0; j < 8; j++)
context.strokeRect(i*width/8 + 0.5, j*height/8 + 0.5, width/8, height/8);
centerX = 3;
centerY = 3;
drawPiece(centerX, centerY, 'white', 'black');
Hit.arrayCurrent[3][3] = 'white';
centerX = 3;
centerY = 4;
drawPiece(centerX, centerY, 'black', 'white');
Hit.arrayCurrent[3][4] = 'black';
centerX = 4;
centerY = 3;
drawPiece(centerX, centerY, 'black', 'white');
Hit.arrayCurrent[4][3] = 'black';
centerX = 4;
centerY = 4;
drawPiece(centerX, centerY, 'white', 'black');
Hit.arrayCurrent[4][4] = 'white';
}
使用 drawPiece()
:
function drawPiece(ix, iy, colorIn, colorBorder) {
// Coordinates on canvas :
// x horizontal increasing from left to right
// y vertical increasing from top to bottom
var k = ix*width/8 + width/16;
var l = iy*height/8 + height/16;
// Draw piece
context.beginPath();
context.arc(k, l, radius, 0, 2*Math.PI, false);
context.fillStyle = colorIn;
context.fill();
context.lineWidth = 1;
context.strokeStyle = colorBorder;
context.stroke();
}
我需要修改什么才能将白色和黑色部分居中放置在每个箱子中? 如果我不在棋子图上添加 0.5 个像素,我的棋子和棋子就会模糊。
此外,我还遇到了另一个关于可播放部分渲染不佳的问题,如这张放大图片所示:
您会注意到蓝色部分的白色边框呈现效果不佳,我不知道它可能来自哪里正弦我使用的是与经典白色和黑色相同的函数 drawPiece()
件:
function showPlayableHits(HitCurrent, isShowing) {
for (var i = 0; i < 8; i++)
for (var j = 0; j < 8; j++) {
if (HitCurrent.arrayPlayable[i][j] == 'playable') {
if (isShowing)
drawPiece(i, j, HitCurrent.playableColor, HitCurrent.playableBorderColor);
else
deleteHit(i, j);
}
}
}
最佳答案
浏览器不能很好地处理小数像素的渲染
您遇到的问题源于使用 0.5px
。在某些浏览器上,它会向下舍入,其他浏览器向上舍入,有些朝一个方向移动。看看这个 Stack Overflow post to see an explanation of why fractional pixels work this way.
我对此的解决方案是确保容器的像素数始终为奇数,而内部元素的像素数始终为偶数。然后元素应该居中。
关于JavaScript 游戏 - 无法通过 0.5 像素偏移和错误边界渲染进入中心圆圈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51219178/