Home > Software design >  How to transform SVG coordinate system (resize) just like a canvas?
How to transform SVG coordinate system (resize) just like a canvas?

Time:06-30

On canvas, I can render stuff according to one coordinate system and make the CSS render it differently:

var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.moveTo(0, 0);
ctx.lineTo(1920, 1080);
ctx.stroke();
#canvas {
    width: 100px;
    height: 100px;
    border: 1px solid black;
}
<canvas id="canvas" width="1920" height="1080">
Your browser does not support the HTML5 canvas tag.</canvas>

Even though that should be a very diagonal line according to the JS coordinates, the CSS squashes it so that the browser renders it as a square with a 45° diagonal line.

On SVG I cannot do the same thing with CSS.

#svg {
    height: 100px;
    width: 100px;
    border: 1px solid black;
}
<svg id="svg" height="1080" width="1920">
  <line x1="0" y1="0" x2="1920" y2="1080" style="stroke:rgb(255,0,0);stroke-width:2" />
  Sorry, your browser does not support inline SVG.
</svg>

The SVG coordinates are absolute according to the computer screen's pixels.

How can I draw lines in SVG according to the SVG's original width and height properties, but make them render under the SVG's width height → element bounding box transformation?

CodePudding user response:

Use a viewBox to set the SVG's co-ordinate system. Then you can size the SVG to whatever you want.

#svg {
    height: 100px;
    width: 100px;
    border: 1px solid black;
}
<svg id="svg" viewBox="0 0 1920 1080" preserveAspectRatio="none">
  <line x1="0" y1="0" x2="1920" y2="1080" style="stroke:rgb(255,0,0);stroke-width:2" />
  Sorry, your browser does not support inline SVG.
</svg>

CodePudding user response:

You can do something like this

#svg {
    height: 100px;
    width: 100px;
    border: solid black;
}
<svg id="svg" height="1080" width="1920">
  <line x1="0" y1="0" x2="100%" y2="100%" style="stroke:rgb(255,0,0)" />
  Sorry, your browser does not support inline SVG.
</svg>

  • Related