Stefan Walter
Stefan Walter

Reputation: 126

Drawing a line with negative coordinates in SVG.js

I am trying to scale my SVG down width 0.5 and then draw a line from positive to negative coordinates, but it seems that it renders only to x:0 and y:0.

Does SVG.jsnot support drawing with negative coordinates, or am I doing something wrong here?

My code:

const designerDiv = document.getElementById('designerDiv')
var draw = SVG().addTo(designerDiv).attr({width: '100%', height: '100%'})

draw.rect(100, 100).attr({ fill: '#f06' })

draw.scale(0.5, 0.5, 0, 0)

draw.line(-100, -100, 100, 100).stroke({ width: 3, color: '#000' })
draw.line(-100, 100, 100, -100).stroke({ width: 3, color: '#000' })

My outcome: enter image description here

Upvotes: 0

Views: 469

Answers (2)

swatchai
swatchai

Reputation: 18782

You need to set the values of svg's viewBox to cover the plotting area. Here I show the real SVG code.

viewBox is the attribute of the svg element. You will need to define it properly in your implementation with svg.js.

<p>1 Circle: center:(0,0), radius:50<tspan>; Viewport, Top-Left:(0,0); width-height:(150,100)</tspan></p>
<svg width="150" height="100" viewBox="0 0 150 100">
  <style>svg {background-color: lightgray;} </style>
  <ellipse cx="0" cy="0" rx="50" ry="50"></ellipse>
</svg>

<p>2 Circle: center:(0,0), radius:50<tspan>; Viewport, Top-Left:(-75,-50); width-height:(150,100)</tspan></p>
<svg width="150" height="100" viewBox="-75 -50 150 100">
  <ellipse cx="0" cy="0" rx="50" ry="50"></ellipse>
</svg>

Upvotes: 1

Sli4o
Sli4o

Reputation: 234

In SVG, drawing outside the viewBox is allowed, but will not be displayed. The documentation to the viewBox can be found here: https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/viewBox

I believe what you are looking for is:

const designerDiv = document.getElementById('designerDiv')
var draw = SVG().addTo(designerDiv).attr({width: '100%', height: '100%'})

draw.rect(100, 100).attr({ fill: '#f06' }).move(100,100)

draw.scale(0.5, 0.5, 0, 0)

draw.line(0, 0, 300, 300).stroke({ width: 3, color: '#000' })
draw.line(300, 0, 0, 300).stroke({ width: 3, color: '#000' })
<script src="https://cdn.jsdelivr.net/npm/@svgdotjs/[email protected]/dist/svg.min.js"></script>


<div id="designerDiv" style="width: 300px; height: 300px;"></div>

But if you want to work with negative coordinates, you can also just adjust the viewBox.

const designerDiv = document.getElementById('designerDiv')
var draw = SVG().addTo(designerDiv).attr({width: '100%', height: '100%'}).viewbox(-100, -100, 300, 300)

draw.rect(100, 100).attr({ fill: '#f06' }).move(-50,-50)

draw.scale(0.5, 0.5, 0, 0)


draw.line(-100, -100, 100, 100).stroke({ width: 3, color: '#000' })
draw.line(-100, 100, 100, -100).stroke({ width: 3, color: '#000' })
<script src="https://cdn.jsdelivr.net/npm/@svgdotjs/[email protected]/dist/svg.min.js"></script>


<div id="designerDiv" style="width: 300px; height: 300px;"></div>

Upvotes: 2

Related Questions