画布到图像src上的base64

时间:2016-05-24 06:01:16

标签: javascript html5 image canvas base64

我想将rawImg转换为base64并将其传递给image.src。我将需要base64 dataURL将效果放在我的画布上。 请参阅下面的代码:

function onLoad() {
    canvas = document.querySelector("#myCanvas");
    context = canvas.getContext("2d"); 

    var image = new Image();
    image.onload = function () {
      if (image.width != canvas.width)
        canvas.width = image.width;
      if (image.height != canvas.height)
        canvas.height = image.height;
      context.clearRect(0, 0, canvas.width, canvas.height);
      context.drawImage(image, 0, 0, canvas.width, canvas.height);
      filterCanvas(imageFilter);
    }

    var rawImg = "flower.jpg";
    imageURL = <-- (convert rawImg to base64.. I dont know what to write here)
    image.src = imageURL;


 }  

2 个答案:

答案 0 :(得分:4)

  

使用HTMLCanvasElement.toDataURL()以类型参数指定的格式返回包含图像表示的数据URI(默认类型为image/png

function onLoad() {
  canvas = document.querySelector("#myCanvas");
  context = canvas.getContext("2d");
  var image = new Image();
  image.onload = function() {
    if (image.width != canvas.width)
      canvas.width = image.width;
    if (image.height != canvas.height)
      canvas.height = image.height;
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.drawImage(image, 0, 0, canvas.width, canvas.height);
    filterCanvas(imageFilter);
    var imageURL = canvas.toDataURL();
    YOUR_IMAGE.src = imageURL; //Select `YOUR_IMAGE` using getElementById/querySelector/...
  }
  image.src = "flower.jpg";
}

答案 1 :(得分:0)

使用HTML代码段:

<canvas id="myCanvas"></canvas>
<span>Resultant data URL: </span><span id="result"></span>

并且,更新您的javascript代码如下:

  canvas = document.querySelector("#myCanvas");
  context = canvas.getContext("2d");
  var image = new Image();
  image.onload = function() {
    if (image.width != canvas.width)
      canvas.width = image.width;
    if (image.height != canvas.height)
      canvas.height = image.height;
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.drawImage(image, 0, 0, canvas.width, canvas.height);
   // filterCanvas(imageFilter);
    var imageURL = canvas.toDataURL();
    alert(imageURL);
    document.querySelector("#result").innerHTML = imageURL;
  }
  image.src = "flower.jpg";

您将在#result span元素中获得结果base64字符串。请试试这个。