【问题标题】:How to get bounding box coordinates for canvas content?如何获取画布内容的边界框坐标?
【发布时间】:2017-10-02 23:14:31
【问题描述】:

我有一张带地图的画布。用户可以在该画布中绘制(红色),最终结果将是:

在用户绘制完他想要的任何内容后,我需要计算所有内容的边界框坐标,以便最终获得:

现在我可以遍历画布的每个像素并根据每个非空像素计算边界框,但这是一个相当繁重的操作。有更好的逻辑来实现预期结果的想法吗?

【问题讨论】:

    标签: html html5-canvas


    【解决方案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>

    【讨论】:

    • 需要尝试一下,但看起来绝对是个不错的答案!干得好!
    • @CarlosAlvesJorge 进展如何?
    • 如何将此逻辑应用于画布中已绘制的图像/圆形/任何形状?这是我的问题链接:stackoverflow.com/questions/50136647/…
    猜你喜欢
    • 1970-01-01
    • 2021-04-04
    • 2020-03-03
    • 1970-01-01
    • 2021-01-05
    • 1970-01-01
    • 2019-09-18
    • 2017-11-16
    • 1970-01-01
    相关资源
    最近更新 更多