HTML5 Canvas方格图案

时间:2014-12-27 11:51:07

标签: javascript canvas html5-canvas

我正在尝试创建一个复古的像素化背景画。 “像素”的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) );
            }

        }
    }
}

3 个答案:

答案 0 :(得分:3)

你的逻辑没什么问题。我将在下面解释一下。

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循环在一行中绘制块。
    • 2 * j * w + (i % 2 ? 0 : w)每隔一行移动每个块的x坐标。

答案 1 :(得分:0)

像这样遍历行和列:

for (let column = 0; column < board.columns; column++) {
  for (let row = 0; row < board.rows; row++) {

  }
}

,如果满足以下任一条件,则通过绘制矩形来创建方格图案:

  • 行是偶数,列是奇数
  • 行是奇数,列是偶数

在代码中:

if (row % 2 === 0 && column % 2 === 1 || row % 2 === 1 && column % 2 === 0) {
  canvas.context.rect(
    column * column_width,
    row * row_height,
    column_width,
    row_height
  );
}

const canvas = {
  element: document.querySelector("canvas"),
  context: document.querySelector("canvas").getContext('2d')
}

const board = {
  rows: 15,
  columns: 17,
  colors: {
    light: '#a3cf53',
    dark: '#abd55a'
  }
}

canvas.context.beginPath();
canvas.context.fillStyle = board.colors.dark;
canvas.context.rect(0, 0, canvas.element.width, canvas.element.height);
canvas.context.fill();

canvas.context.beginPath();
canvas.context.fillStyle = board.colors.light;
for (let column = 0; column < board.columns; column++) {
  for (let row = 0; row < board.rows; row++) {
    if (row % 2 === 0 && column % 2 === 1 || row % 2 === 1 && column % 2 === 0) {
      canvas.context.rect(
        column * canvas.element.width / board.columns,
        row * canvas.element.height / board.rows,
        canvas.element.width / board.columns,
        canvas.element.height / board.rows
      );
    }
  }
}
canvas.context.fill();
body {
  margin: 0;
}
<canvas width="595" height="525"></canvas>

答案 2 :(得分:0)

要为正方形提供不同的颜色,我们可以使用以下事实:在(1,1),(2,2),(3,3)处的对角正方形将具有相同的颜色,而(1,2),( 2,3),(3,4)将具有相同的颜色。我们在这里注意到一种模式,在 array(30) { [0]=> array(52) { ["resource_state"]=> int(2) ["athlete"]=> array(2) { ["id"]=> int(2224878) ["resource_state"]=> int(1) } ["name"]=> string(6) "Easy 5" ["distance"]=> float(5037.7) ["moving_time"]=> int(1493) ["elapsed_time"]=> int(1494) ["total_elevation_gain"]=> float(11.1) ["type"]=> string(3) "Run" ["workout_type"]=> int(0) ["id"]=> int(3862655039) ["external_id"]=> string(12) "activity.fit" ["upload_id"]=> int(4133211829) ["start_date"]=> string(20) "2020-08-04T11:43:46Z" ["start_date_local"]=> string(20) "2020-08-04T12:43:46Z" ["timezone"]=> string(25) "(GMT+00:00) Europe/London" ["utc_offset"]=> float(3600) ["start_latlng"]=> array(2) { [0]=> float(52.67) [1]=> float(0.94) } ["end_latlng"]=> array(2) { [0]=> float(52.67) [1]=> float(0.94) } ["location_city"]=> NULL ["location_state"]=> NULL ["location_country"]=> string(14) "United Kingdom" ["start_latitude"]=> float(52.67) ["start_longitude"]=> float(0.94) ["achievement_count"]=> int(0) ["kudos_count"]=> int(13) ["comment_count"]=> int(0) ["athlete_count"]=> int(1) ["photo_count"]=> int(0) ["map"]=> array(3) { ["id"]=> string(11) "a3862655039" ["summary_polyline"]=> string(392) "q|n`Ikew" ["resource_state"]=> int(2) } ["trainer"]=> bool(false) ["commute"]=> bool(false) ["manual"]=> bool(false) ["private"]=> bool(false) ["visibility"]=> string(8) "everyone" ["flagged"]=> bool(false) ["gear_id"]=> string(8) "g3671351" ["from_accepted_tag"]=> bool(false) ["upload_id_str"]=> string(10) "4133211829" ["average_speed"]=> float(3.374) ["max_speed"]=> float(6.6) ["average_cadence"]=> float(78) ["has_heartrate"]=> bool(true) ["average_heartrate"]=> float(166.3) ["max_heartrate"]=> float(178) ["heartrate_opt_out"]=> bool(false) ["display_hide_heartrate_option"]=> bool(true) ["elev_high"]=> float(53) ["elev_low"]=> float(46.2) ["pr_count"]=> int(0) ["total_photo_count"]=> int(0) ["has_kudoed"]=> bool(false) ["suffer_score"]=> float(44) } [1]=> array(50) { ["resource_state"]=> int(2) ["athlete"]=> array(2) { ["id"]=> int(2224878) ["resource_state"]=> int(1) } ["name"]=> string(12) "Morning Walk" ["distance"]=> float(10848.7) ["moving_time"]=> int(8095) ["elapsed_time"]=> int(9257) ["total_elevation_gain"]=> float(74.5) ["type"]=> string(4) "Walk" ["id"]=> int(3847387184) ["external_id"]=> string(40) "80B66E48-B4F8-414F-8974-F6F157A09E03.fit" ["upload_id"]=> int(4116320622) ["start_date"]=> string(20) "2020-08-01T08:32:14Z" ["start_date_local"]=> string(20) "2020-08-01T09:32:14Z" ["timezone"]=> string(25) "(GMT+00:00) Europe/London" ["utc_offset"]=> float(3600) ["start_latlng"]=> array(2) { [0]=> float(53.47) [1]=> float(-1.94) } ["end_latlng"]=> array(2) { [0]=> float(53.48) [1]=> float(-1.9) } ["location_city"]=> NULL ["location_state"]=> NULL ["location_country"]=> string(14) "United Kingdom" ["start_latitude"]=> float(53.47) ["start_longitude"]=> float(-1.94) ["achievement_count"]=> int(0) ["kudos_count"]=> int(22) ["comment_count"]=> int(0) ["athlete_count"]=> int(1) ["photo_count"]=> int(0) ["map"]=> array(3) { ["id"]=> string(11) "a3847387184" ["summary_polyline"]=> string(846) "{rjeIlpyJw}@sxFNDFEDUFeAEk@Uo@COBGFE`@AWyAc@eBAWFUIAOQuAaCu@w@]g@_BqBOMIc@@MFOMNG?GCc@i@}AwA{A}AwAkCEQ@SMLMa@?AD?BSLQ?GMPEb@EBGAMO[k@s@cBeBmDyBcHgB_H_@uBo@wCOoC@QFQE?GAOSYg@Oc@g@gCs@cDUy@g@uAm@kAOg@kAqB_@_Ak@gAGYg@kA[eBY_Ay@aBe@u@]c@i@mB[aAQa@]g@]}@IMIg@W_AQoA_@yC[qD_@sFAwC@uKPuBDwB^mHNeBJsBD}DEgEDm@CwAMsBEa@Qy@_@mAOcBMa@L^\dC`@fAKmAGgA[qCYcEQuAYeEYgBWiCQwAUqCi@eFYcDsAgL]mEA}AMkCB{@@yEEkA?iAIoB@_DMyIAwFBsBC{C@kAEoCa@sIk@eISuBUqDg@{FEeAOeA[sDMiAIwBQgAKaBEOICDWAUS}AIqA?YFJ@HDM?eAFe@d@y@Za@Ra@FEJB@BQA{@fAWd@Mb@MpAELDDZpCT`EX|BHpBNjBR`BVnDPrAj@fG`AdN\jJHrA?^I|@Aj@FjB?vFB~A?xBFrDA~CDxBD|DFdBCvCH|Ej@nHR`B\jCRzBTjBRzBZtCb@|EXlCJvAn@|Fv@vIb@pFTrGB`EG|EExAi@fI]|HE`BClIN`FXxEb@rEp@hEd@rBj@z@Vh@fAxDfA~A|@fBJ^l@nC`AhCrAzBp@xAbA`Cl@|BXvAb@vAVhANf@Zt@Nl@Fd@@lADn@^`BTtAh@fCjDhLjAjDp@bBnBjD|AbC|AnBfAhAl@v@xB~BxBhCrAvBf@dABRERg@f@M^MdAQdAItA@b@h@z@Ll@" ["resource_state"]=> int(2) } ["trainer"]=> bool(false) ["commute"]=> bool(false) ["manual"]=> bool(false) ["private"]=> bool(false) ["visibility"]=> string(8) "everyone" ["flagged"]=> bool(false) ["gear_id"]=> string(8) "g6163360" ["from_accepted_tag"]=> bool(false) ["upload_id_str"]=> string(10) "4116320622" ["average_speed"]=> float(1.34) ["max_speed"]=> float(2.7) ["has_heartrate"]=> bool(true) ["average_heartrate"]=> float(91.6) ["max_heartrate"]=> float(118) ["heartrate_opt_out"]=> bool(false) ["display_hide_heartrate_option"]=> bool(true) ["elev_high"]=> float(276.7) ["elev_low"]=> float(208.7) ["pr_count"]=> int(0) ["total_photo_count"]=> int(0) ["has_kudoed"]=> bool(false) ["suffer_score"]=> float(15) } 中,如果$response3 = curl_exec($curl3); // cURL request which gives me json curl_close($curl3); $runs = json_decode($response3, true); // turning that json into the array // the for and foreach loop i'm trying to use and insert on each loop. The db is connected further up on this page. //Completely open that everything below this is wrong, i've been banging my head against a wall trying everything. open to any suggestions $keys = array_keys($runs); for($i = 0; $i < count($runs); $i++) { foreach($runs[$keys[$i]] as $key => $value) { $stmt = $conn->prepare("INSERT INTO runs (userReferenceRuns, runName, runDate, runDistance, runDuration) VALUES (?, ?, ?, ?, ?)"); $stmt->bind_param("sssss", $_SESSION['userReference'], $names, $startdate, $distances, $movingtime); $stmt->execute(); } } (col, row)均为偶数或均为奇数,则正方形具有相同的颜色(白色),否则它们具有其他颜色(黑色)。 / p>

代码逻辑:

col

row
if ((i % 2 == 0 && j % 2 == 0) || (i % 2 != 0 && j % 2 != 0)){
    square is white/color1
}
else{
    square is black/color2
}