是否有一种方法将html渲染成PNG那样的图像?我知道这是可能的与画布,但我想渲染标准的html元素,如div为例。


当前回答

仅用JavaScript无法100%准确地做到这一点。

有一个Qt Webkit工具,还有一个python版本。如果你想自己做,我已经成功地用可可:

[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];
}];

希望这能有所帮助!

其他回答

这里所有的答案都使用第三方库,而在纯Javascript中将HTML渲染为图像可以相对简单。在MDN的画布部分甚至有一篇关于它的文章。

诀窍是这样的:

使用包含XHTML的foreignObject节点创建SVG 将图像的src设置为该SVG的数据url 将图像绘制到画布上 将画布数据设置为目标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('<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.createElement('img') body.appendChild(targetImg) function onTempImageLoad(e){ ctx.drawImage(e.target, 0, 0) targetImg.src = canvas.toDataURL() }

需要注意的一些事情

The HTML inside the SVG has to be XHTML For security reasons the SVG as data url of an image acts as an isolated CSS scope for the HTML since no external sources can be loaded. So a Google font for instance has to be inlined using a tool like this one. Even when the HTML inside the SVG exceeds the size of the image it wil draw onto the canvas correctly. But the actual height cannot be measured from that image. A fixed height solution will work just fine but dynamic height will require a bit more work. The best is to render the SVG data into an iframe (for isolated CSS scope) and use the resulting size for the canvas.

你可以使用像wkhtmltopdf这样的HTML转PDF工具。然后你可以使用像imagemagick这样的PDF图像工具。不可否认,这是服务器端,一个非常复杂的过程…

使用这段代码,它一定会工作:

<脚本type = " text / javascript”> 美元(文档)。Ready (function () { setTimeout(函数(){ downloadImage (); }, 1000) }); 函数downloadImage () { html2canvas (document.querySelector(“# dvContainer”))。然后(canvas => { a = document.createElement('a'); document.body.appendChild(一个); A.download = "test.png"; a.href = canvas.toDataURL(); a.click (); }); } > < /脚本

不要忘记在你的程序中包含Html2CanvasJS文件。 https://html2canvas.hertzen.com/dist/html2canvas.js

使用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();
        });

来源:http://www.freakyjolly.com/convert-html-document-into-image-jpg-png-from-canvas/

使用剧作家的page.screen()可以非常容易地截取屏幕截图。例如使用Python(但它也适用于Node.js, Java和.NET):

from playwright.async_api import async_playwright

async with async_playwright() as p:
     browser = await p.chromium.launch()
     page = await browser.new_page()
     await page.goto('https://google.com')
     await page.screenshot(path=f'screenshot.png')
     await browser.close()