【问题标题】:How to position a button at the bottom of a bounding rectangle in canvas如何在画布中的边界矩形底部放置一个按钮
【发布时间】:2020-05-24 21:40:15
【问题描述】:

我正在努力在画布顶部放置一个按钮,但比我在画布上绘制的边界矩形略低,我有变量bboxXbboxYbboxWidth、@ 987654326@ 这是我画布中边界矩形的属性。我正在使用getBoundingClientRect() 获取画布的偏移量并将其添加到画布中边界框的坐标,但按钮位置不正确。如何按我想要的方式定位按钮?

这就是我想要实现的目标:

const video = <HTMLVideoElement> document.getElementById("vid");

const canvas = <HTMLCanvasElement> document.getElementById("canvas");

const ctx = canvas.getContext("2d");

ctx.drawImage(this.video, 0, 0, canvas.width,canvas.height);

ctx.strokeStyle = "#00FFFF";
ctx.lineWidth = 2;
ctx.strokeRect(bboxX, bboxY, bboxWidth, bboxHeight);

let rect = canvas.getBoundingClientRect();

let positionX = (bboxX + rect.left).toString() + "px";
let positionY = (bboxY + rect.top).toString() + "px";

document.getElementById("button").style.visibility = "visible";
document.getElementById("button").style.top = positionY;
document.getElementById("button").style.left = positionX;
canvas{
    position: absolute;
    z-index: 10;
    width: 100%;
    height: 100%;
}

#button{
    position: absolute;
    z-index: 15;
    visibility: hidden;
}
<div>
    <button id="button">Show</button>
    <video hidden id="vid" width="300" height="300"></video>
    <canvas id="canvas"></canvas>
 </div>

【问题讨论】:

    标签: javascript html css canvas


    【解决方案1】:

    我会使用相对位置...
    不清楚为什么在放置按钮时使用canvas.getBoundingClientRect 需要与绘制的矩形而不是整个画布对齐。

    见下面的代码:

    const canvas =  document.getElementById("canvas");
    const ctx = canvas.getContext("2d");
    let bboxX = 20
    let bboxY = 10
    let bboxWidth = 100
    let bboxHeight = 60
    
    ctx.lineWidth = 2;
    ctx.strokeRect(bboxX, bboxY, bboxWidth, bboxHeight);
    
    let rect = canvas.getBoundingClientRect();
    let positionX = (bboxX + bboxWidth/2 -25).toString() + "px";
    
    const button = document.getElementById("button")
    button.style.visibility = "visible";
    button.style.left = positionX;
    #button{
        visibility: hidden;
        position: relative;
        width:50px;
    }
    <div>
        <canvas id="canvas" width="300" height="80"></canvas>
        <br>
        <button id="button" >Show</button>    
     </div>

    该代码中的键是:
    let positionX = (bboxX + bboxWidth/2 -25)
    该中心将按钮与矩形对齐。

    bboxX + bboxWidth/2 是矩形的中心,
    然后我们减去按钮宽度的一半-25

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-26
      • 2017-12-24
      • 2013-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-02
      相关资源
      最近更新 更多