Creating a Dynamic Canvas Rendered to Fit Image Dimensions

I'm struggling with a piece of code that creates an SVG and then displays it on a canvas. Here is the Jsbin Link for reference: https://jsbin.com/lehajubihu/1/edit?html,output

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>JS Bin</title>
    <style>
      #imgNode {
        border: "10px dotted black";
      }
    </style>
  </head>
  <img id="imgNode" style="border: 1px dotted black"></img>
  <body>
    <script>
      const { body } = document;

      const canvas = document.createElement("canvas");
      const ctx = canvas.getContext("2d");

      const tempImg = document.createElement("img");
      tempImg.addEventListener("load", onTempImageLoad);
      tempImg.src =
        "data:image/svg+xml;base64," +
        btoa(
          '<svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%"><foreignObject width="100%" height="100%"><div xmlns="http://www.w3.org/1999/xhtml"><style>em{color:red;}</style><em>I</em> lick <span>cheese</span></div></foreignObject></svg>'
        );

      const targetImg = document.querySelector("#imgNode")

      function onTempImageLoad(e) {
        ctx.drawImage(e.target, 0, 0);
        targetImg.src = canvas.toDataURL();
      }
    </script>
  </body>
</html>

Although the code runs smoothly, I noticed that the width and height of the rendered image are fixed and not dynamic. This results in extra space around the HTML content as visible in this image:

My question is, how can I adjust the width and height to make the image/canvas render only the HTML content without any additional space?

Answer №1

When working on your image rendering function onTempImageLoad(e), consider incorporating the following code snippet:

function onTempImageLoad(e) {
        canvas.width = tempImg.width;
        canvas.height = tempImg.height;
        
        ctx.drawImage(e.target, 0, 0);
        targetImg.src = canvas.toDataURL();
      }

It's important to review your SVG as it may contain unnecessary spaces. Initially set at 300x150 pixels, you can test by adjusting the size of the SVG in pixels through replacing width="100%" and height="100%".

tempImg.src =
        "data:image/svg+xml," +
        encodeURIComponent(
          '<svg xmlns="http://www.w3.org/2000/svg" width="100px" height="50px"><foreignObject width="100%" height="100%"><div xmlns="http://www.w3.org/1999/xhtml"><style>em{color:red;}</style><em>I</em> like <span>cheese</span></div></foreignObject></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

Adaptive Design - Content Fragmentation

I am currently working on a webpage layout that has the following HTML structure: <div class="row"> <div class="col3">test 1</div> <div class="col3">test 2</div> <div class="col3">test 3</div> </div ...

Chat box custom scrollbar always positioned at the bottom

I have a personalized chat box where I included overflow-y for scrolling functionality. However, every time I input a message in the text box, it displays at the top of the scrollbar window. Is there a way to automatically show the most recent message I ...

Unable to change background-image as intended

Here is an example of my HTML code with an initial background image: <div id="ffff" style="width: 200px; height: 200px; background-image: url('/uploads/backroundDefault.jpg')">sddsadsdsa<br>dffdsdfs</div> Everything seems to b ...

Cannot seem to get my AJAX code working correctly to show comments

Having some trouble with my comment system code. The PHP part is working fine, comments are being inserted into the table without any issues. However, I am struggling with the Ajax part. The comments are not being displayed unless the page is reloaded. C ...

When trying to implement appDir and withPWA in next.config.js, an error has been encountered

My next.config.js is set up with next-pwa and an experimental app feature included. const withPWA = require('next-pwa'); module.exports = withPWA({ pwa: { dest: 'public', disable: process.env.NODE_ENV === 'development&ap ...

Error: The route cannot be established within an asynchronous function

The following code snippet is from the api.js module, responsible for creating a test route: 'use strict'; module.exports = function (app) { console.log("before route creation"); app.get("/api/test", (req, res) => { ...

What is the best way to display a removed item from the Redux state?

Display nothing when the delete button is clicked. The issue seems to be with arr.find, as it only renders the first item regardless of which button is pressed, while arr.filter renders an empty list. reducer: export default function reducer(state = initi ...

Utilize jQuery to toggle classes on multiple elements in web development

I've been struggling to streamline this code I created for the website's navigation. As a novice in Javascript and jQuery, I would appreciate any help or advice. Thank you! Since the page doesn't reload, I have implemented the following met ...

What could be the reason behind ng-bind-html only displaying text and not the link?

Utilizing ng-repeat to exhibit a list on my webpage. One of the fields in my data contains a URL that I want to display as an actual link within my HTML page. Please refer to the screenshots below: My HTML: My rendered page: I have included the angular- ...

Trouble arises with the MUI 5 date picker when inputFormat is included

When I select a date from the calendar, everything works fine. However, if I set inputFormat="yyyy/MM/dd" and manually type in the date, it doesn't recognize the date format properly. Instead, it treats the input as a string like 11111111111 ...

Error occurs in Typescript when attempting to store data in a record using a pointer

When working with nodes and organizing them into a tree structure, I encounter an issue: This is the definition of the interface: interface IDataObj { children: IDataObj[], frontmatter : { type: string, title: string, path: string}, name: str ...

Is it mandatory to employ the spread operator in the process of updating an object while using the useState hook?

Recently delving into hooks, I stumbled upon an insightful passage in the official documentation regarding Using Multiple State Variables: It is noteworthy that updating a state variable in hooks replaces it entirely, as opposed to merging it like in th ...

dynamic webpage resizing using html and css

Looking for a way to make my SharePoint window automatically resize when the user changes their browser size. I'm using the web version of SharePoint at work and don't have access to Designer. <style type="text/css"> #dgwrap { HEIGHT: ...

Click on each item within the v-for loop to gather relevant information, and subsequently iterate through the collected data

Within a v-for loop, I have implemented a button that, when clicked, retrieves specific data. The objective is to display this data below or in place of the clicked button. <div v-for="(item, index) in items" :key="index"> <button @click="fetch ...

The gap separating the three columns in the DIVs structure

Here is an example that I need The images are being loaded from a MySQL while loop, and I want the spacing between them to be such that the left column and right column touch each side with the middle image centered. Just like in the picture :D This is m ...

Display some text after a delay of 3 seconds using setTimeOut function in ReactJS

When using React JS, I encountered an issue where I am able to display text in the console after 2 seconds, but it is not appearing in the DOM. const items = document.getElementById("items"); const errorDisplay = () => { setTimeout(function () { item ...

Animating Font Awesome content through CSS transitions

I am looking to animate a font awesome pseudo element on my website. Below is the HTML code I am working with: <li class="has-submenu"> <a onclick="$(this).toggleClass('open').closest('.has-submenu').find('.submenu&a ...

Storing information when an object is indexed in a for loop, to be retrieved later when

My JavaScript code includes an AJAX call that takes user input from a form and uses it to search for a JSON object. The matching objects are then displayed in a datalist successfully. Everything is working well so far, but now I want to extract specific f ...

Addressing simple JavaScript "async" AJAX requests that are sequenced and reliant on each other

I'm currently developing an application that includes a dashboard on its main page. In order to address any potential loading issues, the content of the dashboard is being calculated asynchronously using Ajax. This means that users do not have to wait ...

What is the correct way to create a card outline in Bootstrap?

I am currently developing a Django website to enhance my skills in coding, CSS, Html, and Bootstrap. However, I am encountering an issue with the main page of my site. The visuals on my cards do not align properly with the colored boxes at the top of the p ...