如何在HTML5 Canvas'Text上添加边框?

时间:2022-05-04 18:15:35

I can draw text using the below code,

我可以使用下面的代码绘制文字,

myCanvas.fillStyle = "Red";
myCanvas.font = "30pt Arial";
myCanvas.fillText("Some Text", 10, 30);

But I want to add a border around "Some Text", any ideas on that?

但我想在“Some Text”周围添加一个边框,有什么想法吗?

3 个解决方案

#1


31  

Use strokeText() and the strokeStyle. eg:

使用strokeText()和strokeStyle。例如:

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

context.fillStyle = 'red';
context.strokeStyle = 'black';

context.font = '20pt Verdana';
context.fillText('Some text', 50, 50);
context.strokeText('Some text', 50, 50);

context.fill();
context.stroke();
<canvas id="myc"></canvas>

#2


4  

We can use strokeStyle method to draw border around the text or outline, and We can use lineWidth method to define the width of the stroke line.

我们可以使用strokeStyle方法在文本或轮廓周围绘制边框,我们可以使用lineWidth方法来定义笔划线的宽度。

 <script>
  var canvas = document.getElementById('Canvas01');
  var ctx = canvas.getContext('2d');

  ctx.strokeStyle= "red"; //set the color of the stroke line 
  ctx.lineWidth = 3;  //define the width of the stroke line
  ctx.font = "italic bold 35pt Tahoma"; //set the font name and font size
  ctx.strokeText("*",30,80); //draw the text

 </script>
</body>

#3


-2  

What about

关于什么

myCanvas.style.border = "red 1px solid";

#1


31  

Use strokeText() and the strokeStyle. eg:

使用strokeText()和strokeStyle。例如:

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

context.fillStyle = 'red';
context.strokeStyle = 'black';

context.font = '20pt Verdana';
context.fillText('Some text', 50, 50);
context.strokeText('Some text', 50, 50);

context.fill();
context.stroke();
<canvas id="myc"></canvas>

#2


4  

We can use strokeStyle method to draw border around the text or outline, and We can use lineWidth method to define the width of the stroke line.

我们可以使用strokeStyle方法在文本或轮廓周围绘制边框,我们可以使用lineWidth方法来定义笔划线的宽度。

 <script>
  var canvas = document.getElementById('Canvas01');
  var ctx = canvas.getContext('2d');

  ctx.strokeStyle= "red"; //set the color of the stroke line 
  ctx.lineWidth = 3;  //define the width of the stroke line
  ctx.font = "italic bold 35pt Tahoma"; //set the font name and font size
  ctx.strokeText("*",30,80); //draw the text

 </script>
</body>

#3


-2  

What about

关于什么

myCanvas.style.border = "red 1px solid";