是否可以在<canvas>中缩放文本而不会被屏幕大小分解?

时间:2017-01-31 01:51:15

标签: javascript html5 canvas

有人对编码和第一次海报也不熟悉。我一直在写一本关于画布的书,并决定尝试制作一个简单的按钮&#34;页面本质上会拉出一个随机的&#34; true&#34;或&#34; false&#34;。

我设置canvas.width / height以匹配innerwindow。一切都是无缝的,因为我有一个resize事件,除了文本,因为它保持静态。我知道我可以根据屏幕的分辨率以一种方式进行设置,但正如我所提到的那样,当我调整窗口大小时,我正在寻找完全无缝的东西,因此文本显示为&#34;按钮&#34 ;并随之扩展。我尝试过使用context.scale但没有用。有可能吗?

&#13;
&#13;
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);
&#13;
<html >
<head >
<title>Page Title</title>
  <style>
    canvas {
      border: 1px solid black;
    }
  </style>
</head>
<body >

  <canvas  id="draw" ></canvas>
</body>
</html>
&#13;
&#13;
&#13;

谢谢大家!

1 个答案:

答案 0 :(得分:0)

更改

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 Docs

相关问题