我正在尝试创建复古像素化背景画。 “像素”的 x 和 y 位置相应地是奇数和偶数。这似乎适用于 4 的分辨率(res 变量),然后 % 运算符似乎不起作用。
function drawPixelatedBackground()
{
var res = 5;
for (var x=0; x<settings.width/res;x++ )
{
for (var y=0;y<settings.height/res;y++)
{
if ( (x%2==0) && (y%2==0) )
{
nx = x * (settings.width/res);
ny = y * (settings.width/res);
ctx.fillStyle= settings.colors.Fill;
ctx.fillRect(nx,ny, nx+ (settings.width/res),ny+ (settings.height/res) );
}
}
}
}
最佳答案
你的逻辑有点问题。我将在下面解释我的。
http://jsfiddle.net/2eee9moq/2/
function drawCheckeredBackground(can, nRow, nCol) {
var ctx = can.getContext("2d");
var w = can.width;
var h = can.height;
nRow = nRow || 8; // default number of rows
nCol = nCol || 8; // default number of columns
w /= nCol; // width of a block
h /= nRow; // height of a block
for (var i = 0; i < nRow; ++i) {
for (var j = 0, col = nCol / 2; j < col; ++j) {
ctx.rect(2 * j * w + (i % 2 ? 0 : w), i * h, w, h);
}
}
ctx.fill();
}
var canvas = document.getElementById("canvas");
drawCheckeredBackground(canvas);
<canvas id="canvas" width="300" height="300"></canvas>
- 嵌套的
for
循环将 block 绘制成一行。2 * j * w + (i % 2 ? 0 : w)
每隔一行移动每个 block 的 x 坐标。
关于javascript - HTML5 Canvas 方格图案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27666936/