簡體   English   中英

是否可以縮放內部文本 <canvas> 而不按屏幕尺寸細分?

[英]Is it possible to scale text inside <canvas> without breaking it down by screen size?

編碼新手和首次發布者。 我一直在研究一本畫布上的書,並決定嘗試制作一個簡單的“按鈕”頁面,該頁面本質上會拉出隨機的“ true”或“ false”。

我將canvas.width / height設置為與內部窗口匹配。 一切都是無縫的,因為除了文本,我有一個resize事件,因為它保持靜態。 我知道我可以根據屏幕的分辨率以某種方式進行設置,但是如上所述,我正在尋找一種完全無縫的東西,因為我調整了窗口的大小,以便文本顯示居中於“按鈕”並隨其縮放。 我試着玩context.scale無濟於事。 可能嗎?

 window.addEventListener('resize', function() { canvas.width = window.innerWidth; canvas.height = window.innerHeight; createPage(); }, false); var canvas = document.getElementById("draw"); var context= canvas.getContext("2d"); function createCircle(){ context.beginPath(); // is this doing anything? it was working before i used it context.arc(canvas.width/2,canvas.height/2, canvas.width*(.09),0,360,false ); context.fillStyle="white"; context.fill(); //text context.fillStyle="black"; context.font="bold 1em sans-serif"; context.textBaseline="middle"; //little messy here trying to center the text context.fillText("PUSH", canvas.width*(.44), canvas.height/2); } function createPage(){ canvas.width = window.innerWidth; canvas.height = window.innerHeight; //blue context.fillStyle ="#002db3"; context.fillRect(0,0, canvas.width, canvas.height); //red context.fillStyle ="#cc0000"; context.fillRect(0,0, canvas.width, canvas.height*(0.5)); //circle createCircle(); } //flash white,setTimeout(yes/no) function hopeless(){ context.fillStyle="green"; context.fillRect(0,0, canvas.width, canvas.height); context.fillStyle="black"; context.font="bold 1em sans-serif"; context.textBaseline="middle"; context.fillText("NO ALL IS LOST", canvas.width*(.3), canvas.height/2); setTimeout(createPage,1000); } function hope(){ context.fillStyle="blue"; context.fillRect(0,0, canvas.width, canvas.height); context.fillStyle="black"; context.font="bold 1em sans-serif"; context.textBaseline="middle"; context.fillText("YES THERE IS HOPE YET", canvas.width*(.2), canvas.height/2); setTimeout(createPage,1000); } function yesOrNo(){ if(Math.random()<.50){ context.fillStyle="white"; context.fillRect(0,0, canvas.width, canvas.height); setTimeout(hopeless,100); }else{ context.fillStyle="white"; context.fillRect(0,0, canvas.width, canvas.height); setTimeout(hope,100); } } createPage(); canvas.addEventListener("click",yesOrNo); 
 <html > <head > <title>Page Title</title> <style> canvas { border: 1px solid black; } </style> </head> <body > <canvas id="draw" ></canvas> </body> </html> 

感謝大家!

更改

context.fillText("PUSH", canvas.width*(.44), canvas.height/2);

至:

var btnText = "PUSH";
var btnTextSize = context.measureText(btnText);
var textX = (canvas.width / 2) - (btnTextSize.width / 2);
var textY = (canvas.height / 2);
context.fillText(btnText, textX, textY);

MeasureText API文檔

暫無
暫無

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

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