HTML画布 - 在间隔后绘制形状

时间:2017-05-07 17:59:32

标签: javascript html canvas html5-canvas setinterval

下面的脚本绘制了4个弯曲的矩形,其中包含图像。尽管在调用绘制它们的函数之前使用f is Future setInterval毫秒,它会立即绘制它们。我希望立即绘制第一个矩形(即左上角),然后在那个之后绘制其他矩形(每2.5秒绘制一个)。为什么这个功能不能做到这一点,怎么做呢?任何帮助将不胜感激。



2500

var c=document.getElementById('game'),
		ctx=c.getContext('2d');

var images = ['https://i.stack.imgur.com/tXmPa.png', 'https://i.stack.imgur.com/KGhCL.png', 'https://i.stack.imgur.com/s5xu4.png', 'https://i.stack.imgur.com/g6BO0.jpg']

var curvedRect = function(id, selectionnum, x, y, w, h) {
  this.id = id;
  this.selectionnum = selectionnum;
  this.x = x;
  this.y = y;
  this.w = w;
  this.h = h;
}

curvedRect.prototype.makeCurvedRect = function() {
  var img=new Image();
  img.src=images[this.selectionnum];
  ctx.beginPath();
  ctx.lineWidth='8';
  ctx.strokeStyle='white';
  ctx.moveTo(this.x+10, this.y);
  ctx.lineTo(this.x+this.w-10, this.y);
  ctx.quadraticCurveTo(this.x+this.w, this.y, this.x+this.w, this.y+10);
  ctx.lineTo(this.x+this.w, this.y+this.h-10);
  ctx.quadraticCurveTo(this.x+this.w, this.y+this.h, this.x+this.w-10, this.y+this.h);
  ctx.lineTo(this.x+10, this.y+this.h);
  ctx.quadraticCurveTo(this.x, this.y+this.h, this.x, this.y+this.h-10);
  ctx.lineTo(this.x, this.y+10);
  ctx.quadraticCurveTo(this.x, this.y, this.x+10, this.y);
  ctx.stroke();
  ctx.drawImage(img, this.x+2.5, this.y+2.5, this.w-5, this.h-5);
}

var Paint = function(element) {
  this.element = element;
  this.shapes = [];
}

Paint.prototype.addShape = function(shape) {
  this.shapes.push(shape);
}

Paint.prototype.render = function() {
  ctx.clearRect(0, 0, this.element.width, this.element.height);

  for (var i=0; i<this.shapes.length; i++) {
    try {
      setInterval(this.shapes[i].makeCurvedRect(), 2500);
    }
    catch(err) {}
  }
}

var paint = new Paint(c);
var img1 = new curvedRect(1, 0, 200, 55, 150, 150);
var img2 = new curvedRect(2, 1, 375, 55, 150, 150);
var img3 = new curvedRect(3, 2, 200, 230, 150, 150);
var img4 = new curvedRect(4, 3, 375, 230, 150, 150);

paint.addShape(img1);
paint.addShape(img2);
paint.addShape(img3);
paint.addShape(img4);

paint.render();
&#13;
canvas {
  z-index: -1;
  margin: 1em auto;
  border: 1px solid black;
  display: block;
  background: #FF9900;
}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

替换

setInterval(this.shapes[i].makeCurvedRect(), 2500);

立即执行makeCurvedRect()并为setInterval()提供带有绑定函数的返回值

setTimeout(curvedRect.prototype.makeCurvedRect.bind(this.shapes[i]), 2500 * i);

或胖箭头功能

setTimeout(() => this.shapes[i].makeCurvedRect(), 2500 * i);

每个矩形的延迟增加2500.