I want to generate green squares on canvas and then put a white "X" inside all of them. The problem is that when i use my writeX()
function with coordinates inside the square the text doesn't appear. How can I solve this?
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]);
}
}
Assuming your positions
variable is an Array
:
var positions = ['0;0', '61;0', '121;0', '0;61', '61;61', '121;61']
And currentSquares
is a number which reflects the amount of possible positions:
var currentSquares = positions.length
This runs:
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.