HTML5等待画布加载,然后找到base64

时间:2019-01-10 05:44:47

标签: javascript html5 html5-canvas

添加等待直到加载完整画布,然后找到该画布的base64,而不是使用时间。

function make_base(bg_img, width, height)
{
return new Promise(function(resolve, reject) {
  base_image = new Image();
  base_image.src = bg_img;
  base_image.onload = function(){
  ctx.drawImage(base_image, 0, 0, width, height);
  resolve()
  }
  })
}

function loadCanvas(width, height) {
    canvas = document.getElementById('canvas');
    canvas.id = "canvas";
    canvas.width = width;
    canvas.height = height;
    ctx = canvas.getContext("2d");
    canvas.style.zIndex   = 8;
    setTimeout(function() {
    base64 = canvas.toDataURL("image/jpeg",1);
    console.log(base64);
}, 3500);
}

function fillText(name, x_name, y_name, name_color, name_font) {
ctx.fillStyle = name_color;
ctx.font = name_font;
ctx.fillText(name, x_name, y_name);
}

这里的画​​布有时需要一些时间才能加载。由于我为base64 Url设置了3.5秒,有时画布内容没有加载,但是我得到了空白的base64。

function work() {
loadCanvas(x,y)
make_base(xxxxx).then(function () {
fillText(abcd)
})
}

如何等待base64加载完整的画布。

2 个答案:

答案 0 :(得分:1)

只需将导出零件移动到另一个函数中,该函数将在Promise链的末尾调用:

var canvas, ctx;

work()
.then(function (url) {
  var img = new Image();
  img.src = url;
  document.body.appendChild(img);
}).catch(console.error);


function export_canvas() {
  base64 = canvas.toDataURL("image/jpeg", 1);
  console.log(base64);
  return base64;
}

function make_base(bg_img, width, height) {
  return new Promise(function (resolve, reject) {
    base_image = new Image();
    base_image.crossOrigin = "anonymous";
    base_image.src = bg_img;
    base_image.onload = function () {
      ctx.drawImage(base_image, 0, 0, width, height);
      resolve();
    }
  });
}

function setupCanvas(width, height) {
  canvas = document.getElementById("canvas");
  canvas.id = "canvas";
  canvas.width = width;
  canvas.height = height;
  ctx = canvas.getContext("2d");
  canvas.style.zIndex = 8;
}

function fillText(name, x_name, y_name, name_color, name_font) {
  ctx.fillStyle = name_color;
  ctx.font = name_font;
  ctx.fillText(name, x_name, y_name);
}

function work() {
  setupCanvas(80, 40);
  return make_base("https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png", 40, 40)
  .then(function () {
    fillText("abcd", 40, 10, "red");
    // ready to export
    return export_canvas();
  });
}
<canvas id="canvas">

答案 1 :(得分:0)

我不知道发生了什么,但这可以可以解决您的问题。

当您获得base64字符串时,您说的是有时空白。好。将该字符串放在BASE64_NOT_READY中,并用它来区分就绪未就绪,如下所示:

var interval = setInterval(function () {
  base64 = canvas.toDataURL("image/jpeg", 1);

  if (base64 !== BASE64_NOT_READY)
  {
    // ready, break interval and proceed
    clearInterval(interval);
    console.log(base64);
  }
}, 100); // check every 100 ms, actual time depends on way too many factors

您需要确定字符串:

var BASE64_NOT_READY = "???";

您可以使用自己的代码来确定它。更换???,您应该会很高兴!