2

即時通訊使用HTML畫布製作應用程序。我嘗試使用jquery的.offset()方法獲得畫布的偏移量,並且沒問題。我的問題是,當我試圖把畫布放在模態上時,offset()返回0 ...我如何獲得布拉內模式內正確的畫布偏移量?在引導模式中使用偏移量模式返回零

canvas = document.getElementById('canvas'); 
context = canvas.getContext('2d'); 
canvasOffset=$("#canvas").offset(); 
offsetX=canvasOffset.left; 
offsetY=canvasOffset.top; 

canvasOffset返回頂部和左側爲零......

回答

2

您必須等待模式通過使用shown.bs.modal事件引導被positionned。該模式沒有定位過,因此畫布的位置爲0。

入住此示例:

// As soon as the modal is shown 
 
$('#myModal').on('shown.bs.modal', function() { 
 
    // Get the right offset 
 
    var offset = $("#canvas").offset(); 
 
    $('body').append("<br>offset:" + offset.top + ", " + offset.left); 
 
}); 
 

 
// On page load offset is 0, 0 
 
var offset = $("#canvas").offset(); 
 
$('body').append("<br>offset:" + offset.top + ", " + offset.left);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> 
 
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" /> 
 

 
<!-- Button trigger modal --> 
 
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal"> 
 
    Launch demo modal 
 
</button> 
 

 
<!-- Modal --> 
 
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> 
 
    <div class="modal-dialog" role="document"> 
 
    <div class="modal-content"> 
 
     <div class="modal-header"> 
 
     <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span> 
 
     </button> 
 
     <h4 class="modal-title" id="myModalLabel">Modal title</h4> 
 
     </div> 
 
     <div class="modal-body"> 
 
     <canvas id="canvas" width="150" height="150" color="pink"></canvas> 
 
     </div> 
 
     <div class="modal-footer"> 
 
     <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> 
 
     </div> 
 
    </div> 
 
    </div> 
 
</div>