JS canvas无意中拉伸div

时间:2017-03-14 12:35:24

标签: javascript jquery html css canvas

我有一个持有图像的div。图像本身稍后加载:

HTML

<div id="image_holder" class='hide'>
    <img id="image" onload="createStimuli() " >
    <canvas id="canvasOverImage" class="coveringCanvas" ></canvas>
</div>

覆盖帆布风格:

CSS

.coveringCanvas { 
    position:relative;
    z-index:2 
}

接下来,当时间合适时,我会加载图像。

document.getElementById('image').src = `imagesource`;

因为现在加载了图片,所以它会触发createStimuli()

function createStimuli() {
    var image = $('#image');        
    var canvas = $('#canvasOverImage');
    canvas.css({top:`-${image.height()}px`});   // set style via css
    canvas.attr({ "height":image.height(), "width" :image.width()});  // set attr in html
}

此代码将画布精确地放置在图像的顶部(按预期)但看起来在将位置更改为顶部之前,它会放置在图像的下方或旁边,从而拉伸画布。

因此,即使画布位于图像上,画布的创建也会拉伸div,在div下方/旁边留下空白区域。

有没有办法解决这个问题?或者我应该在创建画布后调整div的大小?

2 个答案:

答案 0 :(得分:0)

要解决此问题:

首先将image_holder div position设置为relative。确保所有绝对定位的元素将定位到最后。

然后将画布position设为absolute,将left设置为0

#canvasOverImage {
  position:absolute;
}

您可以在下面的代码段中测试我已经为canva添加了一些边框以查看结果

&#13;
&#13;
document.getElementById('image').src = "https://images-na.ssl-images-amazon.com/images/G/01/img15/pet-products/small-tiles/23695_pets_vertical_store_dogs_small_tile_8._CB312176604_.jpg";

function createStimuli() {
    var image = $('#image');        
    var canvas = $('#canvasOverImage');
    //canvas.css({top:-(image.height()+5)+'px'});   // set style via css
    canvas.attr({ "height":image.height(),"width" :image.width()});
}
&#13;
#image_holder {
  position:relative;
}

#canvasOverImage {
  border:1px solid red;
  position:absolute;
}

 #canvasOverImage {
  left:0;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="image_holder" class='hide'>
    <img id="image" onload="createStimuli() " ><!--
    --><canvas id="canvasOverImage" class="coveringCanvas" ></canvas>
</div>
&#13;
&#13;
&#13;

请注意,我只需删除5像素以适应图像和画布之间的额外空间

答案 1 :(得分:0)

您可以通过以下方式以更有效的方式完成此类工作......

&#13;
&#13;
document.getElementById('image').src = "https://s-media-cache-ak0.pinimg.com/736x/52/30/66/523066972863437c1a5daa774d1e5414.jpg";

function createStimuli(e) {
    var canvas = $('#canvasOverImage')[0];
    // set canvas css style
    canvas.style.marginLeft = -(e.width + 3) + 'px'; // 3 ~ border width
    // set canvas attr in html
    canvas.width = e.width;
    canvas.height = e.height;
    // draw text on canvas *proves canvas is on top*
    var ctx = canvas.getContext('2d');
    ctx.fillStyle = 'black';
    ctx.font = 'bold 18px Arial';
    ctx.fillText('hello', 10, 25);
}
&#13;
.coveringCanvas {
  border: 3px solid black;
}
.hide {
  display: flex;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="image_holder" class='hide'>
    <img id="image" onload="createStimuli(this)">
    <canvas id="canvasOverImage" class="coveringCanvas"></canvas>
</div>
&#13;
&#13;
&#13;