将 dom 转换svg_如何从DOM转换为SVG坐标并再次返回

将 dom 转换svg

All the cool kids are using Scalable Vector Graphics. SVGs are great until you want to mix DOM and vector interactions — then life becomes more complicated.

所有很酷的孩子都在使用可伸缩矢量图形。 SVG很棒,除非您想将DOM和矢量交互混合在一起-然后生活变得更加复杂。

SVGs have their own coordinate system. It is defined via the viewbox attribute, e.g. viewbox="0 0 800 600" which sets a width of 800 units and a height of 600 units starting at (0, 0). If you position this SVG in an 800×600 pixel area, each SVG unit maps directly to a screen pixel.

SVG具有自己的坐标系。 它是通过viewbox属性定义的,例如viewbox="0 0 800 600" ,其设置从(0,0)开始的800单位的宽度和600单位的高度。 如果将此SVG放置在800×600像素区域中,则每个SVG单元将直接映射到屏幕像素。

However, the beauty of vector images is they can be scaled to any size. Your SVG could be scaled in a 400×300 space or even stretched beyond recognition in a 100×1200 space. Adding further elements to an SVG becomes difficult if you don’t know where to put them.

但是,矢量图像的优点在于它们可以缩放到任意大小。 您的SVG可以在400×300的空间中缩放,甚至可以超出100×1200的空间。 如果您不知道将它们添加到SVG的位置,则很难。

(SVG coordinate systems can be confusing – Sara Soueidan’s viewport, viewBox and preserveAspectRatio article describes the options.)

(SVG坐标系可能会令人困惑-Sara Soueidan的视口,viewBox和preserveAspectRatio文章介绍了这些选项。)

简单分离的SVG协同 (Simple Separated SVG Synergy)

You may be able to avoid translating between coordinate systems entirely.

您也许可以避免完全在坐标系之间转换。

SVGs embedded in the page (rather than an image or CSS background) become part of the DOM and can be manipulated in a similar way to other elements. For example, given a basic SVG with a single circle:

嵌入页面(而不是图像或CSS背景)中的SVG成为DOM的一部分,并且可以通过与其他元素类似的方式进行操作。 例如,给定一个基本的SVG和一个圆圈:

<svg id="mysvg" xmlns="https://www.w3.org/2000/svg" viewBox="0 0 800 600" preserveAspectRatio="xMidYMid meet">
  <circle id="mycircle" cx="400" cy="300" r="50" />
<svg>

we can apply CSS effects:

我们可以应用CSS效果:

circle {
  stroke-width: 5;
  stroke: #f00;
  fill: #ff0;
}

circle:hover {
  stroke: #090;
  fill: #fff;
}

and attach event handlers to modify their attributes:

并附加事件处理程序以修改其属性:

var mycircle = document.getElementById('mycircle');

mycircle.addEventListener('click', function(e) {
  console.log('circle cli
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值