如何仅将画布放在中心对齐的图像上而不是整个页面上?

时间:2016-06-14 20:03:04

标签: angularjs canvas fabricjs

在我的应用程序中使用angularjs并将fabric.js用于画布功能。

这是我的HTML代码:

<div id="imageContainer" style=" width: 100%; height: 90vh; overflow: hidden">
      <img id="imageId" align="middle" ng-src="{{image}}" on-load="setCanvasOnLoad()"/>
</div>
<div id="canvas-section">
      <canvas id="drawingCanvas"></canvas>
</div>

我的图片在页面中间对齐。但是,画布遍布页面。这是我如何在图像上创建画布:

 var deferred = $q.defer();
    $timeout(function () {

    var image = angular.element(document.querySelectorAll("#reboxImage"))[0];
                var drawingCanvasObject = angular.element(document.querySelectorAll("#drawingCanvas"))[0];
                var canvasContainer = angular.element(document.querySelectorAll("#canvas-section"))[0];

                drawingCanvasObject.width = image.offsetWidth;
                drawingCanvasObject.height = image.offsetHeight;

                canvasContainer.top = image.getBoundingClientRect().top;
                canvasContainer.left = image.getBoundingClientRect().left;
                drawingCanvasObject.style.zIndex = 15;
                drawingCanvasObject.style.position = "absolute";
                if (drawingCanvasObject.width > 0 && drawingCanvasObject.height > 0) {
                    if (!MyService.getCanvas()) {
                        MyService.setCanvas(new fabric.Canvas('drawingCanvas', {selection: false}));
                    }
                }

    return deferred.promise;

#canvas-section的CSS如下:

#canvas-section{
    z-index: 10;  /* <- higher than your canvases if it needs to go on top */
    position: absolute;
   left: 0;
    top: 0;
}

我们如何确保画布的宽度,高度,位置,左侧,顶部等始终与图像对齐?

附图: enter image description here

1 个答案:

答案 0 :(得分:1)

您可以将'canvas-section'元素放在'imageContainer'元素中,并将'imageContainer'添加到样式'position:relative'。在这种情况下,您将使用绝对但相对于图像容器的画布定位。

<强>更新

尝试重新排列代码,如下所示:

.wrapper {
  text-align: center;
  width: 100%;
  }

.centered-wrapper {
  height: 230px;
  display: inline-block;
  position: relative;
  }

.content-covering-image {
  color: #fff;
  position: absolute;
  left: 0;
  top: 20px;
  }
<div class="wrapper">
  <div class="centered-wrapper">
  <img src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcRQZHFAgf3rw0Eg_Mdx3PaGUYd4-9BB1fr503Tg0wjbivpFDTthSw"/>
  
  <span class="content-covering-image">canvas</span>
  </div>
</div>

当然使用适合您目的和风格的类名。