在带有背景图像的画布上绘制一个矩形

时间:2017-11-06 21:39:17

标签: javascript html5 angular typescript canvas

我目前正致力于以下项目: 我正在从我的计算机上传一张图片,然后我在画布上显示在我的页面上。现在我想做的就是在图片上绘制一些矩形并获得它们的坐标。

然而,似乎我绘制的矩形在某种程度上落后于背景图片。我可以看到(在控制台中)创建的div位于画布(矩形)内,但它没有显示在背景图像上。我试图改变z-index,但这似乎没有帮助。

有谁知道我做错了什么?这甚至是那样的吗?

(我从here获得了矩形绘图代码)

这是我目前为止的代码(ts):

export class AppComponent {
  title = 'app';

  public buildings = [ ];
  public showUploader = true;

  constructor() { }

  public getImages() {
    this.buildings = document.getElementById('imageImport')['files'];
    const reader = new FileReader();

    reader.onload = function (e) {
      const canvas: any = document.getElementById('imageCanvas');
      const ctx = canvas.getContext('2d');
      const img: any = new Image();
      img.onload = function () {
        canvas.width = img.width;
        canvas.height = img.height;
        ctx.drawImage(img, 0, 0);
      };
      img.src = e.target['result'];
    };
    reader.readAsDataURL(this.buildings[0]);
    this.showUploader = false;
    this.initDraw(document.getElementById('imageCanvas'));
  }

  public initDraw(canvas) {
    function setMousePosition(e) {
      const ev = e || window.event;
      if (ev.pageX) {
        mouse.x = ev.pageX + window.pageXOffset;
        mouse.y = ev.pageY + window.pageYOffset;
      } else if (ev.clientX) {
        mouse.x = ev.clientX + document.body.scrollLeft;
        mouse.y = ev.clientY + document.body.scrollTop;
      }
    }

    const mouse = {
      x: 0,
      y: 0,
      startX: 0,
      startY: 0
    };
    let element = null;

    canvas.onmousemove = function (e) {
      setMousePosition(e);
      if (element !== null) {
        element.style.width = Math.abs(mouse.x - mouse.startX) + 'px';
        element.style.height = Math.abs(mouse.y - mouse.startY) + 'px';
        element.style.left = (mouse.x - mouse.startX < 0) ? mouse.x + 'px' : mouse.startX + 'px';
        element.style.top = (mouse.y - mouse.startY < 0) ? mouse.y + 'px' : mouse.startY + 'px';
      }
    };

    canvas.onclick = function (e) {
      if (element !== null) {
        element = null;
        canvas.style.cursor = 'default';
        console.log('finsihed.');
      } else {
        console.log('begun.');
        mouse.startX = mouse.x;
        mouse.startY = mouse.y;
        element = document.createElement('div');
        element.className = 'rectangle';
        element.style.left = mouse.x + 'px';
        element.style.top = mouse.y + 'px';
        canvas.appendChild(element);
        canvas.style.cursor = 'crosshair';
      }
    };
  }

}

和html:

  <input id="imageImport" type="file" multiple="multiple" (change)=getImages() *ngIf="showUploader"/>

  <div>
      <canvas id="imageCanvas"> </canvas>
  </div>

0 个答案:

没有答案