2017-10-02 3 views
0

지도가있는 캔버스가 있습니다. 이 캔버스에서 사용자는 (빨간색) 그릴 수 있으며, 최종 결과는 다음과 같습니다 사용자 후캔버스 내용의 경계 상자 좌표를 가져 오는 방법은 무엇입니까?

enter image description here

그는 내가 그렇게 모든 콘텐츠의 경계 상자의 좌표를 계산해야 원하는 어떤 그려진 나는 궁극적 할 수 :

enter image description here

지금 할 수있는 루프 캔버스의 모든 픽셀을 통해 모든 비어 있지 않은 픽셀을 기준으로 경계 상자를 계산하지만, 이것은 매우 무거운 작업입니다. 의도 한 결과를 얻기위한 더 나은 논리에 대한 아이디어?

답변

1

그려지는 점과 점의 지름을 추적 할 수 있습니다. 그런 다음 최소/최대 경계.

이렇게하는 한 가지 방법은 그려지는 위치와 반경 (브러쉬) 또는 경계 (불규칙한 모양)를 추적 한 다음 현재 최소/최대 경계와 병합하여 필요한 경우 새 바인딩을 업데이트하는 것입니다. "푸싱 "항상 내부와 일치하는 범위.

var ctx = c.getContext("2d"), 
 
    div = document.querySelector("div > div"), 
 

 
    // keep track of min/max for each axis 
 
    minX = Number.MAX_SAFE_INTEGER, 
 
    minY = Number.MAX_SAFE_INTEGER, 
 
    maxX = Number.MIN_SAFE_INTEGER, 
 
    maxY = Number.MIN_SAFE_INTEGER, 
 
    
 
    // brush/draw stuff for demo 
 
    radius = 10, 
 
    rect = c.getBoundingClientRect(), 
 
    isDown = false; 
 

 
ctx.fillText("Draw something here..", 10, 10); 
 
ctx.fillStyle = "red"; 
 
c.onmousedown = function() {isDown = true}; 
 
window.onmouseup = function() {isDown = false}; 
 
window.onmousemove = function(e) { 
 
    if (isDown) { 
 
    var x = e.clientX - rect.left; 
 
    var y = e.clientY - rect.top; 
 
    
 
    // When something is drawn, calculate its impact (position and radius) 
 
    var _minX = x - radius; 
 
    var _minY = y - radius; 
 
    var _maxX = x + radius; 
 
    var _maxY = y + radius; 
 
    
 
    // calc new min/max boundary 
 
    if (_minX < minX) minX = _minX > 0 ? _minX : 0; 
 
    if (_minY < minY) minY = _minY > 0 ? _minY : 0; 
 
    if (_maxX > maxX) maxX = _maxX < c.width ? _maxX : c.width; 
 
    if (_maxY > maxY) maxY = _maxY < c.height ? _maxY : c.height; 
 
    
 
    // show new bounds 
 
    showBounds(); 
 
    
 
    // draw something 
 
    ctx.beginPath(); 
 
    ctx.arc(x, y, radius, 0, 6.28); 
 
    ctx.fill(); 
 
    } 
 
}; 
 

 
function showBounds() { 
 
    // for demo, using bounds for display purposes (inclusive bound) 
 
    div.style.cssText = 
 
    "left:" + minX + "px;top:" + minY + 
 
    "px;width:" + (maxX-minX-1) + "px;height:" + (maxY-minY-1) + 
 
    "px;border:1px solid blue"; 
 
}
div {position:relative} 
 
div > div {position:absolute;pointer-events:none}
<div> 
 
    <canvas id=c width=600 height=600></canvas> 
 
    <div></div> 
 
</div>

+0

그것을 밖으로 시도해야하지만, 확실히 좋은 대답처럼 보인다! 잘 했어! –

+0

@CarlosAlvesJorge 어떻게 됐습니까? – K3N

관련 문제