Javascript 将HTML呈现到图像

Javascript 将HTML呈现到图像,javascript,html,css,image,render,Javascript,Html,Css,Image,Render,有没有一种方法可以将html呈现为类似PNG的图像?我知道使用canvas是可能的,但我想呈现标准的html元素,比如div。您可以使用html到PDF工具,比如wkhtmltopdf。然后,您可以使用PDF格式的图像转换工具,如imagemagick。诚然,这是服务器端,是一个非常复杂的过程…我不认为这是最好的答案,但它似乎足够有趣,可以发布 编写一个应用程序,打开您最喜爱的浏览器以显示所需的HTML文档,正确调整窗口大小,并拍摄屏幕截图。然后,删除图像的边框。是。存在以将HTML呈现到(然后

有没有一种方法可以将html呈现为类似PNG的图像?我知道使用canvas是可能的,但我想呈现标准的html元素,比如div。

您可以使用html到PDF工具,比如wkhtmltopdf。然后,您可以使用PDF格式的图像转换工具,如imagemagick。诚然,这是服务器端,是一个非常复杂的过程…

我不认为这是最好的答案,但它似乎足够有趣,可以发布

编写一个应用程序,打开您最喜爱的浏览器以显示所需的HTML文档,正确调整窗口大小,并拍摄屏幕截图。然后,删除图像的边框。

是。存在以将HTML呈现到
(然后可以将其用作图像)


注意:有一个已知的问题,这将不适用于SVG,仅使用JavaScript无法100%准确地做到这一点

那里有一个Qt网络工具包,还有一个。如果你想自己做,我在可可方面取得了成功:

[self startTraverse:pagesArray performBlock:^(int collectionIndex, int pageIndex) {

    NSString *locale = [self selectedLocale];

    NSRect offscreenRect = NSMakeRect(0.0, 0.0, webView.frame.size.width, webView.frame.size.height);
    NSBitmapImageRep* offscreenRep = nil;      

    offscreenRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:nil
                                             pixelsWide:offscreenRect.size.width
                                             pixelsHigh:offscreenRect.size.height
                                             bitsPerSample:8
                                             samplesPerPixel:4
                                             hasAlpha:YES
                                             isPlanar:NO
                                             colorSpaceName:NSCalibratedRGBColorSpace
                                             bitmapFormat:0
                                             bytesPerRow:(4 * offscreenRect.size.width)
                                             bitsPerPixel:32];

    [NSGraphicsContext saveGraphicsState];

    NSGraphicsContext *bitmapContext = [NSGraphicsContext graphicsContextWithBitmapImageRep:offscreenRep];
    [NSGraphicsContext setCurrentContext:bitmapContext];
    [webView displayRectIgnoringOpacity:offscreenRect inContext:bitmapContext];
    [NSGraphicsContext restoreGraphicsState];

    // Create a small + large thumbs
    NSImage *smallThumbImage = [[NSImage alloc] initWithSize:thumbSizeSmall];  
    NSImage *largeThumbImage = [[NSImage alloc] initWithSize:thumbSizeLarge];

    [smallThumbImage lockFocus];
    [[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];  
    [offscreenRep drawInRect:CGRectMake(0, 0, thumbSizeSmall.width, thumbSizeSmall.height)];  
    NSBitmapImageRep *smallThumbOutput = [[NSBitmapImageRep alloc] initWithFocusedViewRect:CGRectMake(0, 0, thumbSizeSmall.width, thumbSizeSmall.height)];  
    [smallThumbImage unlockFocus];  

    [largeThumbImage lockFocus];  
    [[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];  
    [offscreenRep drawInRect:CGRectMake(0, 0, thumbSizeLarge.width, thumbSizeLarge.height)];  
    NSBitmapImageRep *largeThumbOutput = [[NSBitmapImageRep alloc] initWithFocusedViewRect:CGRectMake(0, 0, thumbSizeLarge.width, thumbSizeLarge.height)];  
    [largeThumbImage unlockFocus];  

    // Write out small
    NSString *writePathSmall = [issueProvider.imageDestinationPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@-collection-%03d-page-%03d_small.png", locale, collectionIndex, pageIndex]];
    NSData *dataSmall = [smallThumbOutput representationUsingType:NSPNGFileType properties: nil];
    [dataSmall writeToFile:writePathSmall atomically: NO];

    // Write out lage
    NSString *writePathLarge = [issueProvider.imageDestinationPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@-collection-%03d-page-%03d_large.png", locale, collectionIndex, pageIndex]];
    NSData *dataLarge = [largeThumbOutput representationUsingType:NSPNGFileType properties: nil];
    [dataLarge writeToFile:writePathLarge atomically: NO];
}];
希望这有帮助

您可以使用,这是一个无头webkit(safari中的渲染引擎和(直到最近)chrome)驱动程序。您可以学习如何进行页面截屏。希望有帮助

我可以推荐这个库吗?它是专门为解决这个问题而编写的(我是维护人员)。
以下是您如何使用它(更多):


您可以将引用添加到项目中并执行以下操作:

string htmlCode ="<p>This is a sample html.</p>";
Image image = HtmlRender.RenderToImage(htmlCode ,new Size(500,300));
string htmlCode=“这是一个示例html。

”; Image Image=HtmlRender.RenderToImage(htmlCode,新大小(500300));
安装phantomjs

$ npm install phantomjs
$ phantomjs github.js
使用以下代码创建一个文件github.js

var page = require('webpage').create();
//viewportSize being the actual size of the headless browser
page.viewportSize = { width: 1024, height: 768 };
page.open('http://github.com/', function() {
    page.render('github.png');
    phantom.exit();
});
将文件作为参数传递给phantomjs

$ npm install phantomjs
$ phantomjs github.js

我为Chrome、Firefox和MS Edge开发的唯一一个库是。与HTML2Canvas相比,它输出的质量更好,并且仍然受到不同于HTML2Canvas的支持

获取元素并下载为PNG

var node= document.getElementById("elementId");
var canvas = document.createElement("canvas");
canvas.height = node.offsetHeight;
canvas.width = node.offsetWidth;
var name = "test.png"

rasterizeHTML.drawHTML(node.outerHTML, canvas)
     .then(function (renderResult) {
            if (navigator.msSaveBlob) {
                window.navigator.msSaveBlob(canvas.msToBlob(), name);
            } else {
                const a = document.createElement("a");
                document.body.appendChild(a);
                a.style = "display: none";
                a.href = canvas.toDataURL();
                a.download = name;
                a.click();
                document.body.removeChild(a);
            }
     });

有很多选择,他们都有自己的优点和缺点

选项1:使用API
  • (基于铬)
  • (有一个html选项)
专业人士

  • 执行Javascript
  • 近完美渲染
  • 在正确使用缓存选项时快速
  • 规模由API处理
  • 精确的时间、视口
  • 大多数时候,他们提供免费计划
缺点

  • 如果你打算大量使用它们,就不是免费的
选项2:使用众多可用库中的一个
  • (包含在wkhtmltopdf工具中)
  • (适用于ruby并基于wkhtmltoimage)
  • (适用于python并基于wkhtmltoimage)
专业人士

  • 大多数情况下,转换速度相当快
缺点

  • 糟糕的渲染
  • 不执行javascript
  • 不支持最新的web功能(FlexBox、高级选择器、web字体、框大小、媒体查询等)
  • 有时安装起来并不那么容易
  • 复杂的
选项3:使用PhantomJs,或者使用包装器库
  • (PhantomJs的javascript包装库)
专业人士

  • 执行Javascript
  • 相当快
缺点

  • 糟糕的渲染
  • 不支持最新的web功能(FlexBox、高级选择器、web字体、框大小、媒体查询等)
  • 复杂的
  • 如果要加载图像,那么让它工作起来就不那么容易了
选项4:使用Chrome Headless和包装库
  • (用于Chrome headless的javascript包装库)
专业人士

  • 执行Javascript
  • 近完美渲染
缺点

  • 在以下方面不容易获得想要的结果:
    • 页面加载定时
    • 视口尺寸
  • 复杂的
  • 非常慢,如果html包含外部链接,甚至更慢

披露:我是ApiFlash的创始人。我尽力提供了一个诚实而有用的答案。

使用html2canvas只需包含插件和调用方法,将HTML转换为画布,然后作为图像PNG下载

        html2canvas(document.getElementById("image-wrap")).then(function(canvas) {
            var link = document.createElement("a");
            document.body.appendChild(link);
            link.download = "manpower_efficiency.jpg";
            link.href = canvas.toDataURL();
            link.target = '_blank';
            link.click();
        });

来源

使用此代码,它肯定会工作:


$(文档).ready(函数(){
setTimeout(函数(){
下载图像();
},1000)
});
函数downloadImage(){
html2canvas(document.querySelector(#dvContainer)),然后(canvas=>{
a=document.createElement('a');
文件.正文.附件(a);
a、 下载=“test.png”;
a、 href=canvas.toDataURL();
a、 单击();
});	 
}

这里的所有答案都使用第三方库,而将HTML呈现到图像在纯Javascript中可能相对简单。甚至在MDN的画布部分也有

诀窍在于:

  • 使用包含XHTML的foreignObject节点创建SVG
  • 将图像的src设置为该SVG的数据url
  • 在画布上绘制图像
  • 将画布数据设置为target image.src
const{body}=document
const canvas=document.createElement('canvas')
const ctx=canvas.getContext('2d')
canvas.width=canvas.height=100
const tempImg=document.createElement('img')
tempImg.addEventListener('load',onTempImageLoad)
tempImg.src='data:image/svg+xml',+encodeURIComponent('em{color:red;}I lick cheese')
const targetImg=document.createElement('img')
身体。附属物儿童(targetImg)
函数onTempImageLoad(e){
ctx.drawImage(e.target,0,0)
targetImg.src=canvas.toDataURL()

}
我知道这是一个很老的问题,已经有了很多答案,但我仍然花了几个小时试图真正做我想做的事情:

  • 给定一个html文件,从逗号生成背景为透明的(png)图像
    const body = document.getElementsByTagName('BODY')[0];
    const img = document.createElement('img')
    img.src = 'data:image/svg+xml,' + encodeURIComponent(`<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200"><foreignObject width="100%" height="100%"><div xmlns="http://www.w3.org/1999/xhtml" style="border:1px solid red;padding:20px;"><style>em {color:red;}.test {color:blue;}</style>What you see here is only an image, nothing else.<br /><br /><em>I</em> really like <span class="test">cheese.</span><br /><br />Zoom in to check the resolution!</div></foreignObject></svg>`);        
    body.appendChild(img);
    
    import * as htmlToImage from 'html-to-image';
    import download from 'downloadjs';
    
    import logo from './logo.svg';
    import './App.css';
    
    const App = () => {
      const onButtonClick = () => {
        var domElement = document.getElementById('my-node');
        htmlToImage.toJpeg(domElement)
          .then(function (dataUrl) {
            console.log(dataUrl);
            download(dataUrl, 'image.jpeg');
          })
          .catch(function (error) {
            console.error('oops, something went wrong!', error);
          });
      };
      return (
        <div className="App" id="my-node">
          <header className="App-header">
            <img src={logo} className="App-logo" alt="logo" />
            <p>
              Edit <code>src/App.js</code> and save to reload.
            </p>
            <a
              className="App-link"
              href="https://reactjs.org"
              target="_blank"
              rel="noopener noreferrer"
            >
              Learn React
            </a><br></br>
            <button onClick={onButtonClick}>Download as JPEG</button>
          </header>
        </div>
      );
    }
    
    export default App;
    
    <div>
    <div id="capture">
     <p>
        <span>Heading Of Image</span><br></br>
        <span>This is color Image</span><br></br>
        <img src="Your/ImagePath/ifany.jpg" width="100%" />
        <span>Footer Of the Image</span>
     </p>
    </div>
    <h2>Generated Image</h2>
    <div id="real">
    </div></div>
    
    var htmlToImage = require('html-to-image');
    var node = document.getElementById('capture');
    htmlToImage.toJpeg(node, { quality: 1, backgroundColor: "#FFFFFF", height: node.clientHeight, width: node.clientWidth })
        .then(function (dataUrl) {
            var img = new Image();
            img.src = dataUrl;
            var div = document.getElementById("real")
            div.appendChild(img)
        })
        .catch(function (error) {
            console.error('oops, something went wrong!', error);
        });