如何将数据网址从画布图像附加到表格的背景图像

时间:2013-12-01 19:22:10

标签: html5 html5-canvas

我无法将画布图像中的dataurl附加到表格的背景图像

这是我的画布功能

var container=document.getElementById("pageContainer")
var origCanvas=document.getElementById("page1");
origCanvas.setAttribute("style", "position:absolute;border:1px solid black");
var wmContext = origCanvas.getContext('2d');
wmContext.globalAlpha=0.5;
// setup text for filling
wmContext.font = "72px Comic Sans MS" ;
wmContext.fillStyle = "red";
// get the metrics with font settings
var metrics = wmContext.measureText("@ViewBag.entityTitle");
var width = metrics.width;
// height is font size
var height = 72;

// change the origin coordinate to the middle of the context
wmContext.translate(origCanvas.width/2, origCanvas.height/2);
// rotate the context (so it's rotated around its center)
wmContext.rotate(-Math.atan(origCanvas.height/origCanvas.width));
// as the origin is now at the center, just need to center the text
wmContext.fillText("@ViewBag.entityTitle", -width / 2, height / 2);

    //DataUrl = origCanvas.toDataURL("image/png");
    var dataURL = origCanvas.toDataURL("image/png");
    document.getElementById('my').src = dataURL;
    var data = atob(DataUrl.substring("data:image/png;base64,".length)),
     asArray = new Uint8Array(data.length);

    for (var i = 0, len = data.length; i < len; ++i) {
        asArray[i] = data.charCodeAt(i);
    }

    var blob = new Blob([asArray.buffer], { type: "image/png" });

    var img = document.createElement("img");

    img.src = (window.webkitURL || window.URL).createObjectURL(blob);

    $('#my').appendChild(img);

我在这里获得画布的图像

 <img id="my"/>

现在我希望这个图像作为我的表格或div的背景,如何做到这一点?

1 个答案:

答案 0 :(得分:1)

如果你想使用canvas作为div的背景,你可以这样做:

// get a reference to the div you want to apply the background to

var myDiv=document.getElementById("anyDiv");

// create a url string from your origCanvas

var url="url("+origCanvas.toDataURL()+")";

// apply the url as the background of your div

myDiv.style.backgroundImage=url; 

顺便说一句,您可以将origCanvas.toDataURL用作img.src(不需要代码中的所有转换):

img.src=origCanvas.toDataURL();