Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

javascript - Saving <div> as image: html-to-image captures div only with transparent space around it

I have a page in Gatsby, which holds a big div with a h1. I have installed html-to-image as well as save-html-as-image (which internally uses the former) and tried this with both libraries separately. I am trying to convert the blue div + h1 into a png image.

Here is the code:

import { saveAsPng, saveAsJpeg } from "save-html-as-image"

const IndexPage = () => {
  const convertToImage = id => {

    let node = document.getElementById(id)
    saveAsPng(node)

  }
  return (
    <Layout>
      <div>
        <div
          id="123"
          style={{ width: "600px", height: "900px", backgroundColor: "blue" }}
        >
          <h1>Hello World</h1>
        </div>
      </div>

      <button onClick={() => convertToImage("123")}>Download</button>
    </Layout>
  )
}
 
export default IndexPage

And here is a screenshot of the site:

enter image description here

However, the image that is being generated looks like this (if opened in Mac OS Preview)

enter image description here

So it gets me the correct image, but I don't understand why there is so much space around it, which seems to be a part of the image. I also tried it without saving the image and appended it directly into the DOM, and the result is the same. The space around it seems to be transparent, but is there.

Not sure what I am doing wrong? I had this working a few months ago, now just opened this project and it has this error. Can't figure it out really.

PS: If somebody could help me to make the screenshots a bit smaller, that would be great

EDIT: I just tried the same code in a new create-react-app, to make sure it's not gatsby thats causing the error, and it produces the same error.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...