'Write text inside rectangle
I am trying to find how to filltext inside a rectangle. Unfortunately i can only find C# projects/tutorials. Is it possible to add text inside a rectangle in HTML5 in a canvas? I want each rectangle (node) to have a different text on it for example 1 is called cow and the other tiger and so on. Is this possible? i have tried everything!
var x = 150;
var y = 100;
var canvas = $('#NodeList').get(0);
var ctx = canvas.getContext('2d');
ctx.font = "30px Arial";
canvas.height = 0;
var rects = [
[20, 20, x, y],
[20, 220, x, y],
[20, 420, x, y],
[20, 620, x, y],
[20, 820, x, y],
[20, 1020, x, y],
[20, 1220, x, y],
[20, 1420, x, y],
[20, 1620, x, y]
];
for (var i = 0; i < rects.length; i++) {
canvas.height = canvas.height + 200;
ctx.clearRect(0, 0, canvas.width, canvas.height);
//rectangles opnieuw tekenen
for (var j = 0; j < i; j++) {
ctx.fillRect(rects[j][0],
rects[j][1],
rects[j][2],
rects[j][3]);
}
ctx.fillRect(rects[i][0],
rects[i][1],
rects[i][2],
rects[i][3]);
}
$('#NodeList').click(function (e) {
var x = e.offsetX,
y = e.offsetY;
for (var i = 0; i < rects.length; i++) {
if (x > rects[i][0] && x < rects[i][0] + rects[i][2] && y > rects[i][1] && y < rects[i][1] + rects[i][3]) {
alert('Vierkant ' + i + ' clicked');
}
}
});
enter code here
Solution 1:[1]
I know its really old question. But I ran into a similar so I decided to post the answer.
Note: You have to treat canvas differently that html tags like div. You get one ctx for canvas and you paint on it like a stream. Just change the position of your next elements and it would as expected.
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
context.beginPath();
context.rect(188, 50, 200, 100);
context.fillStyle = 'red';
context.shadowColor = '#999';
context.shadowBlur = 20;
context.shadowOffsetX = 15;
context.shadowOffsetY = 15;
context.fill();
context.fillStyle = 'black';
context.font = '20px Courier';
context.shadowColor = 'transparent';
context.shadowBlur = 0;
context.shadowOffsetX = 0;
context.shadowOffsetY = 0;
context.fillText(`List item`, 200, 80);
context.lineWidth = 7;
<canvas id="myCanvas" width="578" height="200"></canvas>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ahmad |
