我试图找到如何在矩形内填充文字。不幸的是我只能找到C#项目/教程。是否可以在画布中的HTML5中的矩形内添加文本?我希望每个矩形(节点)上都有不同的文本,例如1叫做cow,另一只叫老虎等等。这可能吗?我已经尝试了一切!
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
我知道它真的很老了。但我遇到了类似的问题所以我决定发布答案。
注意:你必须以不同的方式对待canvas
html
标签,如div
。你为ctx
得到一个canvas
,你就像一条小溪在上面画画。只需更改下一个元素的位置即可。
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>