用js在svg图上的上动态添加一张任意格式的图片

JavaScript013

用js在svg图上的上动态添加一张任意格式的图片,第1张

<?xml version="1.0" standalone="no"?>

<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title>new document </title>

<script type="text/javascript">

function init() {

var svg_obj = document.getElementById("svg_obj")

svg_obj.onclick = function(event) {

var xmlns = "http://www.w3.org/2000/svg"

var tsvg_obj = document.getElementById("svg_obj")

var svg_img = document.createElementNS(xmlns, "image")

svg_img.href.baseVal = "example.jpg"

svg_img.setAttributeNS(null, "x", event.pageX)

svg_img.setAttributeNS(null, "y", event.pageY)

svg_img.setAttributeNS(null, "height", "16px")

svg_img.setAttributeNS(null, "width", "16px")

tsvg_obj.appendChild(svg_img)

}

}

</script>

</head>

<body onload="init()">

<svg id="svg_obj" version="1.1"

xmlns="http://www.w3.org/2000/svg" style="width:220pxheight:220pxborder:1px solid black"></svg>

</body>

</html>

用 JS 获取 SVG 内 path 元素中的图形的实际位置及尺寸的方法:

1、使用getElementById获取svg节点对象:

var el = document.getElementById("yourElement")

2、调用getBoundingClientRect获取path的边界矩形的位置:

var rect = el.getBoundingClientRect()

3、分别获取width和height属性就得到实际位置了。

console.log( rect.width )

console.log( rect.height)