2

I am trying to use toDataURL in Html5 Canvas to export an image to a PNG file in a new window.

Here's my JS code (I think you guys need to see it all to check if there's something wrong)

var oCtx;
var oCanvas;
var img;
var oImg;

function updateClicked() {


    oCanvas.width = oCanvas.width;
    oCtx.drawImage(img,0,0); 

    oCtx.font = "normal 23px arial";     // different font
oCtx.textBaseline = "top";           // text baseline at the top
oCtx.fillStyle = "#666";
oCtx.fillText(document.getElementById("attentionde").value, 255, 365);

oCtx.font = "bold 28px arial";     // different font
oCtx.fillStyle = "red";
oCtx.fillText(document.getElementById("nofacture").value, 172, 226);

}
// setup our test canvas
// and a simple drawing function
window.onload = function() {
    oCanvas = document.getElementById("thecanvas");
    oCtx = oCanvas.getContext("2d");

    var iWidth = oCanvas.width;
    var iHeight = oCanvas.height;

    img=new Image();
    img.src="Fond_Facture_Medio.jpg"; //My background image source

//BACKGROUND-IMAGE//
img.onload = function(){
oCtx.drawImage(img,0,0);  

};

var dataUrl = oCanvas.toDataURL();

var button = document.getElementById("thebutton");
button.onclick =function() {
  window.open(dataUrl, "toDataURL() image", "width=1275, height=1650");
}  
}​

When I click on my button (id="thebutton")...it does open a new window with a PNG file in it, but the png is blank...Seems like it does not get the images drawn in the Canvas for a unknown reason.

I tried adding this code right before the var dataUrl = oCanvas.toDataURL(); line :

oCtx.fillStyle = "rgba(0, 0, 255, .5)";
oCtx.fillRect(25, 25, 125, 125);

Just to test if I was drawing a shape, it would save it through the dataURL process. When I tested it, by clicking on the "thebutton" button, it opened a new window, and voila! I was able to see and save the canvas image with a light-blue rectangle in it...but no backgroud-image, and no text...nothing else. I really don't understand what's wrong. Thank you!

4

1 回答 1

1

移动这条线

var dataUrl = oCanvas.toDataURL();

在 button.onclick 处理程序中。

在您创建数据 URL 的那一刻,window 元素和任何 img 元素都没有触发它的 load 事件,因此没有绘制任何内容。

于 2012-11-05T14:57:04.587 回答