簡體   English   中英

在html5畫布的矩形內對齊文本

[英]Aligning text inside rectangle of html5 canvas

我有可調整大小的矩形,希望在其旁邊有右對齊的文本(天數)。

我現在所擁有的:

我現在有什么

(同樣,在調整文本大小時,文本並沒有真正垂直對齊)

我希望擁有:

我希望擁有的

有沒有辦法填充文本並將其在繪制的矩形內對齊? 也歡迎其他建議。

js.do代碼

        function dayRect(day) {
            const days = ["I","II","III","IV","V","VI","VII"];
            context.beginPath();

            //maybe align the text inside this rect somehow
            context.rect(0, day*h/7, 3*w/27, h/7);

            context.stroke();
            context.font = "0.5rem Arial";
            context.fillStyle = "#fff";
            context.fillText(days[day], 0, (day+1)*h/7);
        }

由於您看不到任何內容,因此我對您的代碼進行了一些更改。 您需要為文本使用context.textAlign="right"並將其移動到其他位置。 希望對您有所幫助。

  function getMousePos(canvas, evt) { var rect = canvas.getBoundingClientRect(); return { x: evt.clientX - rect.left, y: evt.clientY - rect.top }; } var canvas = document.getElementById("posHourCanvas"); var context = canvas.getContext('2d'); canvas.width=600,canvas.height=300; var boxes = []; function init() { context.clearRect(0, 0, canvas.width, canvas.height); boxes.length = 0; const strokeWidth = 0.6; //canvas.width = $('#two')[0].clientWidth; var cellSize = canvas.width/27; canvas.height = 7/27 * canvas.width; var x = y = 0; draw(x,y,canvas.width,canvas.height,cellSize,strokeWidth); } function Box(x, y, day, hour) { this.x = x; this.y = y; this.day = day; this.hour = hour; } function draw(x, y, w, h, cellSize, strokeWidth) { let onePixel = cellSize * strokeWidth; cellSize = cellSize * (1 - strokeWidth); context.beginPath(); context.lineWidth = 1; context.strokeStyle = 'rgba(0, 0, 0, 1)'; const rectCoordinates = { x: x+3*w/27, y: y, w: w-3*w/27, h: h } context.rect(rectCoordinates.x, y, rectCoordinates.w, h); context.fillStyle = 'white'; context.fill(); context.stroke(); let offX = rectCoordinates.w/24 + rectCoordinates.x; let offY = h/7; for (let i = 0; i < 7; i++) { dayRect(i); context.beginPath(); context.moveTo(0, offY); context.lineTo(w, offY); context.strokeStyle = "black"; context.stroke(); offY+=h/7; } for (let i = 0; i < 24; i++) { context.beginPath(); context.moveTo(offX, 0); context.lineTo(offX, h); context.stroke(); offX+=rectCoordinates.w/24; } function dayRect(day) { const days = ["I","II","III","IV","V","VI","VII"]; context.beginPath(); context.rect(0, day*h/7, 3*w/27, h/7); context.stroke(); context.font = "0.5rem Arial"; context.fillStyle = "#fff"; context.textAlign="right"; context.fillText(days[day], 60, (day+1)*h/7); } } init(); 
 body { margin: auto; color: white; background-color: black; min-height: 100vh; } 
 <div id="parent"> <div>text above</div> <div id="two"> <canvas id="posHourCanvas" width="600" height="300"></canvas> </div> <div>text under</div> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM