使用javascript将html文本渲染到位图而不使用服务器端代码

时间:2014-01-19 08:24:45

标签: javascript jquery html canvas html5-canvas

我需要使用javascript代码将文章,html中的帖子转换为最终用户作为位图,有没有办法做到这一点,没有服务器端代码?

示例:

<p> testing text here .... </p>

1 个答案:

答案 0 :(得分:2)

您可以使用例如html2canvas将您的网页转换为位图。

如果您的HTML不包含任何外部引用,您还可以使用以下函数:

/**
 *    Canvas extension: drawHTMLText(txt, options)
 *    By Ken Nilsen, Epistemex
 *    http://epistemex.com/
 *
 *    USAGE:
 *        myContext.drawHTMLText(txt [, options]);
 *
 *    var options = {x: startPosition,
 *                   y: startPosition,
 *                   width: maxWidth,
 *                   height: maxHeight,
 *                   callback: myFunction,
 *                   callbackError: myErrorFunction}
 *
 *    Each individual option is optional in themself. The callback
 *    on success contains an object with reference to result and
 *    originalText. Error callback is provided with the error object.
 *
 *    License: MIT
 */

CanvasRenderingContext2D.prototype.drawHTMLText = function(txt, options) {

    /// make sure we have an object if none was provided
    options = options || {};

    var ctx = this,

        /// build inline SVG
        iSVG =

        '<svg xmlns="http://www.w3.org/2000/svg" width="' +
        (options.width ? options.width : ctx.canvas.width) +

        '" height="' +
        (options.height ? options.height : ctx.canvas.height) +
        '"><foreignObject width="100%" height="100%">' +

        '<div xmlns="http://www.w3.org/1999/xhtml" style="font:' +
        ctx.font + ';color:' + ctx.fillStyle + '">' +

        txt +

        "</div></foreignObject></svg>",

        /// create Blob of inlined SVG
        svg = new Blob([iSVG],{type:"image/svg+xml;charset=utf-8"}),

        /// create URL (handle prefixed version)
        domURL = self.URL || self.webkitURL || self,
        url = domURL.createObjectURL(svg),

        /// create Image
        img = new Image;

    /// handle image loading
    img.onload = function () {

        /// draw SVG to canvas
        ctx.drawImage(img,
                      (options.x ? options.x : 0),
                      (options.y ? options.y : 0));

        domURL.revokeObjectURL(url);

        /// invoke callback if provided
        if (typeof options.callback === 'function')
            options.callback({result: img,
                              originalText: txt});
    };

    /// handle potential errors
    img.onerror = function(e) {
        if (typeof options.callbackError === 'function') {
            options.callbackError(e);
        } else {
            console.log(e);
        }
    }

    img.src = url;
}

<强>用法

var canvas = document.createElement('canvas'),
    ctx = canvas.getContext('2d');

canvas.width = 800;  /// size of your resulting bitmap
canvas.height = 600;

ctx.drawHTMLText(...html here...);

var dataUri = canvas.toDataURL();

dataUri现在包含编码为data-uri的位图(以字符串格式)。此字符串可以发送到服务器或在锚标记上设置为href以及下载属性:

<a id="downloadLink">Click here to download</a>

来自JS:

/// obtain dataUri here
downloadLink.href = dataUri;
downloadLink.download = 'filename.png';

重要提示:您要绘制的HTML代码不得包含任何外部引用(CSS,图像等),因为浏览器会限制SVG由于安全性而被绘制为图像到画布的原因。