简体   繁体   中英

When setting the position of an svg element, in javascript, how to do the "px"?

Say you have a simple fullscreen div

<body>
<div id="wrapper">
</div>
</body>

and

* { margin:0; padding:0; }
html, body { width:100%; height:100%; } /* ensure full screen*/
<style>
    div {
        display: block; width: 100%; height: 100%; margin: 0;
    }
</style>

and then in javascript

var wrapper = document.getElementById('wrapper')
var svgns = "http://www.w3.org/2000/svg"

If you want to add an svg dot on the screen , you would:

(A) make an svg element (for convenience we'll just make it the same size as the circle itself, say 20.20)

console.log("making new dot at 313.172")

onedot = document.createElementNS(svgns, 'svg')
onedot.setAttribute('width', 20)
onedot.setAttribute('height', 20)

onedot.style.position = 'absolute'
onedot.style.left = 312
onedot.style.top = 172

(B) inside the element, just add the one stroke, being the circle.

var cc = document.createElementNS(svgns, "circle")
cc.setAttribute("cx", 10)
cc.setAttribute("cy", 10)
cc.setAttribute("r", 10)
cc.setAttribute("fill", "blue")

onedot.appendChild(cc)

wrapper.appendChild(onedot)

This does seem to work fine. You can now go wild drawing dots all over the place:

在此处输入图像描述

My problem, right here you're dealing with "real world" so to speak values, not just the whacky svg space stuff:

onedot.style.position = 'absolute'
onedot.style.left = 312
onedot.style.top = 172

That's going in the div.

in my limited understanding of DOM, HTML etc. it's really essential to specify such values as "px"

How to specify px there?

Is there a way?

onedot.style.position = 'absolute'
onedot.style.left = 312
onedot.style.top = 172

change to

onedot.style.position = 'absolute';
onedot.style.left = '312px'; // both are oke
onedot.style.top = 172+'px'; // is ok to

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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