当我绘制边界框时,在画布内渲染的图像消失了吗?

时间:2019-01-12 06:25:47

标签: javascript html5-canvas

我正在尝试在画布上渲染的图像上绘制边界框。但是,一旦我绘制边界框,图像就会消失。任何人都可以参考以下代码来帮助我解决此问题:

 PhoneAuthProvider.getInstance().verifyPhoneNumber(
            phoneNumber,        // Phone number to verify
            60,                 // Timeout duration
            TimeUnit.SECONDS,   // Unit of timeout
            this,               // Activity (for callback binding)
            mCallbacks);        // OnVerificationStateChangedCallbacks
    // [END start_phone_auth]

    mVerificationInProgress = true;

注意:我正在渲染尺寸(宽度和高度)大于画布尺寸的图像

1 个答案:

答案 0 :(得分:1)

这就是您的代码要执行的操作

ctx.clearRect(0, 0, canv.width, canv.height); // This clears the canvas
draw();

为避免这种情况,您必须从ctx.drawImage()方法中再次调用draw()

但是最好的办法可能是在启动应用程序之前等待图像加载完毕,这样,img.onload将负责告知资产何时准备就绪,并且您将能够使用该图像,因为绘图应用程序的初始化。

var canv = document.getElementById('canvas1'),
  ctx = canv.getContext('2d'),
  rect = {},
  drag = false,
  img = loadImage(init); // pass the init function as a callback

function loadImage(cb)  {
  var img = new Image();
  img.onload = cb;
  img.src = "https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png";
  return img;
}

function draw() {
  ctx.clearRect(0, 0, canv.width, canv.height); // clear
  ctx.drawImage(img, -200, -100); // draw bg
  drawRect(); // draw rect
}

function drawRect() {
  ctx.strokeRect(rect.startX, rect.startY, rect.w, rect.h);
}

function mouseDown(e) {
  rect.startX = e.pageX - this.offsetLeft;
  rect.startY = e.pageY - this.offsetTop;
  drag = true;
}

function mouseUp() {
  drag = false;
}

function mouseMove(e) {
  if (drag) {
    rect.w = (e.pageX - this.offsetLeft) - rect.startX;
    rect.h = (e.pageY - this.offsetTop) - rect.startY;
    draw();
  }
}

function init() {
  canv.addEventListener('mousedown', mouseDown, false);
  canv.addEventListener('mouseup', mouseUp, false);
  canv.addEventListener('mousemove', mouseMove, false);
  draw();
}
<canvas id="canvas1" width="300" height="300"></canvas>