将图像绘制到画布并通过base64对其进行编码

时间:2019-02-06 14:13:07

标签: javascript html canvas base64

我正在尝试将现有图像绘制到画布上并通过base64对其进行编码。这是我的代码:

var canvas = document.createElement("canvas");
canvas.id = "MyCanvas";

document.getElementById("Table1").appendChild(canvas);

var myCanvas = document.getElementById("MyCanvas");
var myCanvasContext = myCanvas.getContext("2d");

myCanvas.width = 135;
myCanvas.height = 170;

var img = new Image();

img.onload = function(){
    myCanvasContext.drawImage(img,0,0);
}

img.src = "https://example.com/asd.png";

var toURL = myCanvas.toDataURL();
console.log(toURL);

它将图像绘制到画布上,但是toURL是空图像base64代码,尺寸为135x170。我尝试对其进行解码,但是它始终显示空白图像。

我找不到问题所在。

2 个答案:

答案 0 :(得分:2)

问题是在实际加载图像之前调用myCanvas.toDataURL();。为此,您需要将其移至onload回调中,例如:

var img = new Image();

img.onload = function(){
    myCanvasContext.drawImage(img,0,0);

    // ...moved here
    var toURL = myCanvas.toDataURL();
    console.log(toURL);
}

img.src = "https://example.com/asd.png";

以下是一个简化的示例:

const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();

img.crossOrigin = "";
img.src = 'https://www.gravatar.com/avatar/8939f42cb6c31e31e570ea8f07fe9757?s=32&d=identicon&r=PG';

img.onload = () => {
  canvas.width = img.naturalWidth;
  canvas.height = img.naturalHeight;

  ctx.drawImage(img, 0, 0);

  console.log(canvas.toDataURL());
};

document.body.appendChild(canvas); // append the canvas ...
document.body.appendChild(img); // ... and img for demo purposes only

答案 1 :(得分:0)

var canvas = document.createElement("canvas");
canvas.id = "MyCanvas";

document.getElementById("Table1").appendChild(canvas);

var myCanvas = document.getElementById("MyCanvas");
var myCanvasContext = myCanvas.getContext("2d");

myCanvas.width = 500;
myCanvas.height = 500;

var img = new Image();

img.onload = function(){
    myCanvasContext.drawImage(img,0,0);
}

img.src = "http://underthebridge.co.uk/wp-content/uploads/2014/03/Example-main-image1.jpg";
var toURL = myCanvas.toDataURL();
console.log(toURL);

var img2 = document.createElement("img");
img2.id = "MyImg";
img2.src = toURL;
document.getElementById("Table1").appendChild(img2);
<div id='Table1'> </div>

您不能将base64放在画布中,而只能在标记img中。