簡體   English   中英

用Javascript-> measureText高度創建的Canvas語音氣泡?

[英]Canvas speechbubble created in Javascript -> measureText height?

我目前正在嘗試使用javascriptcanvas創建語音氣泡

問題一:

我通過以下方式添加寬度: ctx.measureText(text).width + 40以確保ctx.measureText(text).width + 40的寬度是靈活的,並取決於var text = 'Speechbubble test'; 輸入。 還添加40像素左右增加邊距!

如何獲得文本的高度以使其也變得靈活? 我一直在檢查,但找不到與measureText方法類似的東西,而且它似乎不存在。

有什么方法可以獲取文本的實際高度? 我問是因為我打算為其添加換行符。 eG:多行支持(在特定數量的字母后打斷文本行)。

問題2:

我正在嘗試向語音泡沫添加一個語音泡沫方向指針。 對不起,我用這種方式描述它,不知道這個詞是什么。 但是我在談論以下內容:

預覽我正在談論的圖像

如何在語音泡沫中添加以下內容?

感謝您的幫助和幫助。

當前示例:

 var canvas = document.getElementById('canvas'); var ctx = canvas.getContext("2d"); ctx.font = "13px Helvetica"; var text = 'Speechbubble test'; component(ctx, ctx.measureText(text).width, 70, "#37f", 10, 10, 16, text); function component(ctx, width, height, color, x, y, radius, text) { // Variables var width = width + 40; var height = height; var x = x; var y = y; var radius = Math.min(radius, Math.min(width, height) / 2); var color = color; var pi2 = Math.PI * 2; var r = radius; var w = width; var h = height; // Transparent background //ctx.fillStyle = "rgba(255, 255, 255, 0.5)"; ctx.fillStyle = color; ctx.setTransform(1, 0, 0, 1, x, y); // Draw arc ctx.beginPath(); ctx.arc(r , r , r, pi2 * 0.5 , pi2 * 0.75); ctx.arc(w - r, r, r, pi2 * 0.75, pi2); ctx.arc(w - r, h - r, r, 0, pi2 * 0.25); ctx.arc(r , h - r, r, pi2 * 0.25, pi2 * 0.5); ctx.fill(); ctx.setTransform(1, 0, 0, 1, 0, 0); // Text fillstyle ctx.fillStyle = "#fff"; ctx.fillText(text, x + 20, y + 40); } 
 <canvas width="500" height="500" id="canvas"></canvas> 

問題在於,盡管規范定義了一種通過TextMetrics對象測量高度的方法,但目前尚無廠商實際實現它。

因此,我們必須作弊以從字體中獲取實際大小。

一種方法是臨時插入DOM元素並從中獲取高度:

 console.log(getTextHeight("Hello", "20px sans-serif")); function getTextHeight(txt, font) { var el = document.createElement('div'), height; el.style.cssText = "position:fixed;padding:0;left:-9999px;top:-9999px;font:" + font; el.textContent = txt; document.body.appendChild(el); height = parseInt(getComputedStyle(el).getPropertyValue('height'), 10); document.body.removeChild(el); return height } 

與畫布一起使用時,只需傳入context.font作為您的font參數:

var fontHeight = getTextHeight("Hello", ctx.font);

關於問題二:

您可以通過插入lineTo()調用來破壞圓形矩形的底線路徑,例如:

 var ctx = c.getContext("2d"), r = 20, w = 290, h = 100, pi2 = Math.PI*2; var ap = w * 0.2, aw = 20, ah = 30; //arrow position, width, height ctx.translate(1.5,0.5); // Rounded rectangle ctx.beginPath(); ctx.arc(r , r , r, pi2 * 0.5 , pi2 * 0.75); ctx.arc(w - r, r, r, pi2 * 0.75, pi2); ctx.arc(w - r, h - r, r, 0, pi2 * 0.25); // bottom right corner ctx.lineTo(w - ap, h); // inserts an arrow (following clock-wise) ctx.lineTo(w - ap, h + ah); ctx.lineTo(w - ap - aw, h); ctx.arc(r , h - r, r, pi2 * 0.25, pi2 * 0.5); // bottom left corner ctx.closePath(); ctx.stroke(); 
 <canvas id=c></canvas> 

暫無
暫無

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

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