在html5画布的矩形内对齐文本

时间:2019-01-21 11:02:58

标签: javascript html5-canvas text-align

我有一个可调整大小的矩形,我希望在其旁边有右对齐的文本(天数)。

我现在所拥有的:

what I have now

(同样,在调整文本大小时,文本实际上并没有垂直对齐)

我希望拥有的东西:

what I wish to have

是否可以填充文本并将其在绘制的矩形内对齐?也欢迎其他建议。

js.do code

sub

1 个答案:

答案 0 :(得分:1)

由于看不到任何内容,因此我更改了代码中的一些内容。您需要为文本使用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>