如何将包含(图像标记和某些文本)的HTML代码或数据转换为图像以供下载 [英] How to Convert HTML code or data containing (image tag and some text) into image for download

查看:60
本文介绍了如何将包含(图像标记和某些文本)的HTML代码或数据转换为图像以供下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一些Html代码渲染为我的网站下载的图像。我正在使用html2canvas正常工作,为文本创建图像,但我想从html div,img,text,paragraph创建图像。

I want to render some Html code as an image to download for my website. I am using html2canvas that is working fine to create image for text but I want to create image from html div,img,text,paragraph.

我使用下面的代码来将html渲染为图像

I am using below code to render html into image

<!DOCTYPE html>
<html>
<head lang="en">



</head>
<body>
<div><h1>HTML content to render:</h1>

    <div id="content">
        <img src="./images/127597554.jpg" height="200" width="200">
        Hello <strong>visiting</strong> guest
    </div>

</div>
<h1>Existing canvas:</h1>
<canvas width="500" height="200"></canvas>
<script type="text/javascript" src="../dist/html2canvas.js"></script>
<button>Run html2canvas</button>
<script type="text/javascript">
    var canvas = document.querySelector("canvas");
    var ctx = canvas.getContext("2d");
    var ctx = canvas.getContext('2d');
document.querySelector("button").addEventListener("click", function() {
        html2canvas(document.querySelector("#content"), {canvas: canvas}).then(function(canvas) {
            console.log('Drew on the existing canvas');
        });
    }, false);

</script>
</body>
</html>

我尝试了一些第三方api来实现图像,但它们是一个限制。所以我想要实现这使用代码。
我怎样才能实现这个目标。

I tried some third party api to achive the image but their is a limit.So i want to achive this using the code. How can i achive this.

我想要一张下面caode的图片

I want an image of the below caode

<div><h1>HTML content to render:</h1>

    <div id="content">
        <img src="./images/127597554.jpg" height="200" width="200">
        Hello <strong>visiting</strong> guest
    </div>

</div>

我想得到这样的结果

推荐答案

使用 rasterizeHTML.js

来自示例:

<canvas id="canvas" width="400" height="200"></canvas>
<script type="text/javascript">
    var canvas = document.getElementById("canvas");

    rasterizeHTML.drawHTML(
        '<div><h1>HTML content to render:</h1>' + 
        '    <div id="content">' + 
        '        <img src="./images/127597554.jpg" height="200" width="200">' + 
        '        Hello <strong>visiting</strong> guest' + 
        '    </div>' + 
        '</div>',
        canvas);
</script>

或者只是:

rasterizeHTML.drawURL("http://example.net", canvas);

要下载图像,请使用 canvas2image (带有隐藏的画布):

To download the image use canvas2image (with a hidden canvas):

Canvas2Image.saveAsPNG(canvas, width, height);

在客户端上进行渲染的主要优点是html可以是用户特定的和服务器不必渲染图像。

The major advantages of doing the rendering on the client are that the html can be user specific and the server does not have to render the image.

这篇关于如何将包含(图像标记和某些文本)的HTML代码或数据转换为图像以供下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆