画布Square内的文本未显示

时间:2019-04-08 10:54:30

标签: javascript html5-canvas

我想在画布上生成绿色方块,然后在所有方块中放置白色“ X” 。问题是,当我将我的writeX()函数与正方形内的坐标一起使用时,文本不会出现。我该如何解决?

function drawSquare(xR,yR) {   
    ctx.beginPath();
    ctx.fillStyle='rgba(124,252,0,0.5)';
    ctx.fillRect(xR,yR,60,60);
    ctx.strokeRect(xR,yR,60,60)
    ctx.closePath();
}

function writeX(xR,yR) {
    ctx.font = "30px Impact";
    ctx.fillStyle = 'white';
    ctx.textAlign = "center";
    ctx.fillText("X", xR+30,yR+40);
}

function generateSquares() {
    for(i=0;i<currentSquares;i++) {
        var coords=new Array;
        coords=String(positions[i]).split(';',5);
        drawSquare(coords[0],coords[1]);
        writeX(coords[0],coords[1]);
    }
}

1 个答案:

答案 0 :(得分:0)

假设您的positions变量是Array

var positions = ['0;0', '61;0', '121;0', '0;61', '61;61', '121;61']

currentSquares是一个数字,反映了可能的职位数量:

var currentSquares = positions.length

运行:

var positions = ['0;0', '61;0', '121;0', '0;61', '61;61', '121;61']; // pairs of 'X;Y'
var currentSquares = positions.length;

var canvas = document.querySelector('#surface');
var ctx = canvas.getContext('2d');

function toNumber (x) {
  return Number(x);
}

function drawSquare(xR,yR) {   
    ctx.beginPath();
    ctx.fillStyle='rgba(124,252,0,0.5)';
    ctx.fillRect(xR,yR,60,60);
    ctx.strokeRect(xR,yR,60,60)
    ctx.closePath();
}

function writeX(xR,yR) {
    ctx.font = "30px Arial"; // changed "Impact" to "Arial" because "Impact" isn't necessarily installed for every user
    ctx.fillStyle = 'white';
    ctx.textAlign = "center";
    ctx.fillText("X", xR+30,yR+40);
}

function generateSquares() {
    for(var i=0; i < currentSquares; i++) {
        var coords = positions[i].split(';').map(toNumber); // need to cast "positions" pair into Numbers
        drawSquare(coords[0], coords[1]);
        writeX(coords[0], coords[1]);
    }
}

generateSquares();
<canvas id="surface" width="182" height="182"></canvas>