Ways to adjust the SVG coordinate system (resize) to mimic a canvas?

When working with canvas, I have the ability to render objects using one coordinate system while manipulating how CSS displays them:

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 the line should appear as diagonal based on the JavaScript coordinates, CSS compresses it into a square with a 45° diagonal line.

In contrast, when working with SVG, CSS cannot alter the display in the same way.

#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 coordinates in SVG are absolute and correspond directly to the screen's pixels.

Is there a way to draw lines in SVG based on the original width and height properties, but still have them conform to the element bounding box transformation set by the CSS?

Answer №1

Implement a viewBox attribute in the SVG to establish its coordinate system, enabling you to adjust the size of the SVG as desired.

#svg {
    height: 150px;
    width: 150px;
    border: 2px 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:3" />
  Your browser does not support inline SVG.
</svg>

Answer №2

Here is an example of how to achieve 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

NodeJS for CSS Parsing and Selecting

Can anyone recommend a NodeJS library similar to https://github.com/alexdunae/css_parser? I have tried using https://github.com/visionmedia/css, but it doesn't fulfill all my requirements. For example, when I parse the following CSS: .behavior1 {co ...

Exploration of the contents within objects in JavaScript

Currently, I am conducting an experiment on login functionalities using Firebase. So far, I have succeeded in creating user accounts and storing additional information along with them. However, I am facing a challenge when it comes to retrieving this store ...

Are items placed into an array passed by reference or by value?

When working with custom Objects in an Angular context, I define two objects "a" and "b" using an interface. These are created as class attributes along with an empty array of these objects. public a: CustomObj; public b: CustomObj; public array: ...

Generate a segment of HTML content dynamically

My front-end HTML has a section that is dynamically loaded based on the number of entities in the backend. For example, if there are 5 entities in the backend, the div will be repeated 5 times. Currently, this repetition logic is handled by JavaScript. Her ...

Functionality of JavaScript limited within a form

Here is some HTML code I am working with: <div class = "login"> <form> <input type="text" id="username" name="username" placeholder="Username" style="text-align:center"> <br> <br> <input type="pa ...

Issue with anchor tag not functioning properly within toggle div

Can you please help me troubleshoot why the anchor tag is not functioning properly within my div elements? When I click on the first div, the second div is displayed but the anchor tag inside the first div does not seem to be working. <script> $(&ap ...

trouble seeing images with an array input and ngFor in Angular

I am encountering issues while attempting to exhibit an array of images by their source link using ngFor. It seems like there are errors hindering the functionality! Below is the image HTML code located within my card component: <div class="Session-Pa ...

What is the best way to automatically hide the Materialize CSS mobile navbar?

Recently, I completed a website called Link. Using only Materialize CSS, Vanilla JS, and plain CSS, I developed a single-page application that effectively hides and reveals different sections based on event listeners. Everything functions smoothly except ...

ajax is not sending the data to be processed by php

As a newbie to ajax, I have been attempting to submit data for processing and insertion into the database using PHP. Unfortunately, it has not been successful so far and I am unsure of the reasons behind this issue. Here are the steps I've taken up to ...

The dropdown options for the input type file in Vuejs PWA are not appearing

I have created a Vue.js progressive web app that allows users to easily upload images from their mobile phones. While the app typically functions well, there is an issue where upon downloading the app to the homescreen, the image upload feature sometimes b ...

angular-strap sidebar is not showing correctly on navbar-fixed-top

Using angular-strap aside to display a menu that opens from a button on the navbar using bootstrap 3. It was functioning properly until I added the navbar-fixed-top class to the navbar, causing it not to display correctly. Here's the HTML code: < ...

Problem detected in id modification

My JavaScript function is triggered with an onChange event, which works fine when there's only one. <input class="form-control" type="text" onchange="opert(<?php echo $fetch["id_prod"] ?>,1)" id="name" value="<?php echo $fetch["name_prod" ...

The async waterfall is encountering a Typeerror due to the nextcallback function not being defined properly

async.waterfall([1,2,3,4].map(function (arrayItem) { return function (lastItemResult, nextCallback) { // performing the same operation for each item in the array var itemResult = (arrayItem+lastItemResult); // pa ...

Attempting to iterate through an array of HTML5 videos

Having some trouble with my video array - it plays but doesn't loop. I've tried using the HTML video attribute 'loop' and variations like loop="true" and loop="loop" without success. Tonight, all I want is for it to loop properly! var ...

Is it possible to trigger an event just once?

Is there a way to ensure an event only fires once? I recently discovered that using .one seems to do the trick. ...

Next.js application shows 404 errors when trying to access assets within the public directory

I've been struggling to display the favicon for my site (which uses next.js). Despite going through numerous Stack Overflow posts and tutorials, I'm feeling increasingly frustrated. The structure of my project, particularly the public directory, ...

what is preventing me from receiving the props effectively

It's important to note that this question is specifically related to next.js. Understanding Next.js is crucial for grasping the interaction between the getStaticProps and Home functions as shown in the code snippet below. export async function getStat ...

The backdrop hue conceals the dropdown menu background's shade

example I am currently facing an issue related to the appearance of my webpage. The image on the left shows how it looks without a background color set for the element with ID "landing-wrap", while the one on the right includes a background color for the ...

Display the number of rows per page on the pagination system

Looking for a way to add a show per page dropdown button to my existing pagination code from Mui. Here's the snippet: <Pagination style={{ marginLeft: "auto", marginTop: 20, display: "inline-b ...

What is the best way to choose all elements that fall between two specific elements?

Looking to grab content situated between two specific elements within an HTML structure. The HTML snippet in question is as follows... <h2>This is firsty</h2> <p>Some para</p> <ul> <li>list items</li> <li&g ...