简体   繁体   English

SVG 文本元素不可见

[英]SVG text element is not visible

Basically I want to map SVG canvas to -1..1 and print some text on the canvas.基本上我想 map SVG canvas 到 -1..1 并在 ZFCC790C72A86190DE43B3Z 上打印一些文本。

The simple example without mapping requested, is:没有请求映射的简单示例是:

 <style>.text {font: 14pt sans-serif; fill: red;} </style>
 <svg class="text" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <text x="0" y="14pt">TEXT</text> </svg>

What i want is this code to display a text:我想要的是这段代码来显示文本:

 <style>.text {font: 14pt sans-serif; fill: red;} </style>
 <svg class="text" viewBox="-1 -1 2 2" xmlns="http://www.w3.org/2000/svg"> <text x="0" y="0">TEXT</text> </svg>

As I had understand from MDN , the center of the canvas will be at 0,0.正如我从MDN了解到的,canvas 的中心将位于 0,0。 I expect the text string to be printed at the center(above the zero point actually).我希望文本字符串打印在中心(实际上在零点之上)。 I am definitely missing something with this problem.我肯定错过了这个问题。 Can you help me?你能帮助我吗?

As I've commented: your font is too big: 14pt vs the size of the svg canvas: width:2, height:2.正如我所评论的:您的字体太大:14pt 与 svg canvas 的大小相比:宽度:2,高度:2。 In order to understand what happens I've centred the svg canvas in the middle of the window (little square with a silver border) and added overflow:visible;为了了解发生了什么,我将 svg canvas 居中在 window (带银色边框的小方块)的中间,并添加了overflow:visible; so that you can see the text.以便您可以看到文本。

 .text {font: 14pt sans-serif; fill: red;} svg{ border:1px solid silver; width:25px; height:25px; display:block; margin:auto; position:absolute; left:0;right:0;top:0;bottom:0; overflow:visible; }
 <svg class="text" viewBox="-1 -1 2 2" xmlns="http://www.w3.org/2000/svg"> <text x="0" y="0">TEXT</text> </svg>

The solution to your problem is to set a bigger viewBox and a smaller font size.您的问题的解决方案是设置更大的 viewBox 和更小的字体大小。 You may be tempted to use a very small font size for the viewBox you have (-1 -1 2 2).您可能很想为您拥有的 viewBox 使用非常小的字体大小 (-1 -1 2 2)。 Please read this article: The Limits of Numbers in SVG请阅读这篇文章: SVG 中的数字限制

Set the position of the text to the center of the element:将文本的 position 设置为元素的中心:

  1. You can use, x="50%" y ="50%".您可以使用 x="50%" y ="50%"。
  2. Use the text-anchor property to center the text horizontally with the value middle.使用 text-anchor 属性将文本水平居中,值中间。 Here is a simple demo:这是一个简单的演示:

 <svg width="200" height="100"> <rect x="0" y="0" width="200" height="100" stroke="red" stroke-width="3px" fill="white"/> <text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle">TEXT</text> </svg>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM