HTML5 Canvas - 矩形顶部的文本

时间:2014-10-16 17:03:05

标签: html5 canvas

我的代码目前喜欢这个

for(var i = 0; i < data.data.length; i++)
{
        context.beginPath();
        context.fillStyle = '#d0d0d0';
        context.rect(data.data[i].x, data.data[i].y, 200, 25);
        context.fill();
        context.lineWidth = 1;
        context.strokeStyle = 'black';  
        context.stroke();
        context.fillStyle = 'black';
        context.font = 'bold 20px serif';
        context.fillText("1212a", data.data[i].x, data.data[i].y + 20);         
}

用笔划绘制rectnagle,但文本在矩形下方绘制,我尝试更改代码的顺序,但仍在下面...

2 个答案:

答案 0 :(得分:0)

代码似乎没有任何问题。问题可能只是缓存的结果。

var canvas=document.getElementById("main");
var context=canvas.getContext("2d");
var x = 80;
var y = 50;

context.beginPath();
context.fillStyle = '#d0d0d0';
context.rect(x, y, 200, 25);
context.fill();
context.lineWidth = 1;
context.strokeStyle = 'black';  
context.stroke();
context.fillStyle = 'black';
context.font = 'bold 20px serif';
context.fillText("1212a", x, y + 20);
<canvas id="main" width="300px" height="100px">
    This text is displayed if your browser does not support HTML5 Canvas.
</canvas>

答案 1 :(得分:0)

这段代码很好。你的js文件中的其他地方一定有问题。

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');

context.beginPath();
context.fillStyle = '#d0d0d0';
context.rect(50, 50, 200, 25);
context.fill();
context.lineWidth = 1;
context.strokeStyle = 'black';  
context.stroke();
context.fillStyle = 'black';
context.font = 'bold 20px serif';
context.fillText("1212a", 50, 50 + 20);         
<canvas id="canvas"></canvas>