调整文本大小以适合绘制的圆形HTML画布中的切片

时间:2018-04-26 22:22:13

标签: javascript html css canvas

所以我在HTML画布中创建了一个财富之轮。由于我在查询中有多少结果,我将为每个结果创建一个切片,因此它们一起加起来为360度。

通过一些结果,我设法使文本居中,但是当返回更多结果时(例如20-25),每个切片在圆圈中的分量不超过14.4度。然后文本开始相互重叠。

我正在寻找有关如何使function FooClass() { this.data = { foo: null, bar: null, } } let instance = new FooClass(); if (instance instanceof FooClass) { console.log("I am FooClass"); }文本尽可能大的帮助,但同时确保它在切片边框内。

font-size
function rand(min, max) {
  return Math.random() * (max - min) + min;
}

var color = [];
var words = ["Restaurant", "Shop", "Coffe Shop", "Store"];
var label = [];

var nWordsToBeAdded = 40; //Modify this to add or remove n slices to the circle

for(var i = 0; i < nWordsToBeAdded; i++){
  label.push(words[Math.floor(Math.random() * words.length)]);
  if(i % 2 == 0){
    color.push("black");
  }else{
    color.push("red");
  }
}

var slices = color.length;
var sliceDeg = 360/slices;
var deg = rand(0, 360);
var speed = 0;
var slowDownRand = 0;
var ctx = canvas.getContext('2d');
var width = canvas.width; // size
var center = width/2;      // center
var isStopped = false;
var lock = false;

function deg2rad(deg) {
  return deg * Math.PI/180;
}

function drawSlice(deg, color) {
  ctx.beginPath();
  ctx.fillStyle = color;
  ctx.moveTo(center, center);
  ctx.arc(center, center, width/2, deg2rad(deg), deg2rad(deg+sliceDeg));
  ctx.lineTo(center, center);
  ctx.fill();
}

function drawText(deg, text) {
  ctx.save();
  ctx.translate(center, center);
  ctx.rotate(deg2rad(deg));
  ctx.textAlign = "center";
  ctx.fillStyle = "#fff";
  ctx.font = 'bold 30px sans-serif';
  ctx.fillText(text, 130, 10);
  ctx.restore();
}

function drawImg() {
  ctx.clearRect(0, 0, width, width);
  for(var i=0; i<slices; i++){
    drawSlice(deg, color[i]);
    drawText(deg+sliceDeg/2, label[i]);
    deg += sliceDeg;
  }
}

(function anim() {
  deg += speed;
  deg %= 360;

  // Increment speed
  if(!isStopped && speed<3){
    speed = speed+1 * 0.1;
  }
  // Decrement Speed
  if(isStopped){
    if(!lock){
      lock = true;
      slowDownRand = rand(0.994, 0.998);
    } 
    speed = speed>0.2 ? speed*=slowDownRand : 0;
  }
  // Stopped!
  if(lock && !speed){
    var ai = Math.floor(((360 - deg - 90) % 360) / sliceDeg); // deg 2 Array Index
    ai = (slices+ai)%slices; // Fix negative index
    return alert("You got:\n"+ label[ai] ); // Get Array Item from end Degree
  }

  drawImg();
  window.requestAnimationFrame( anim );
}());

document.getElementById("spin").addEventListener("mousedown", function(){
  isStopped = true;
}, false);
body{text-align:center;}
#wheel{
  display:inline-block;
  position:relative;
  overflow:hidden;
}
#wheel:after{
  content:"";
  background:red;
  border:2px solid white;
  position:absolute;
  top:-7px;
  left:50%;
  width:10px;
  height:10px;
  margin-left:-7px;
  transform: rotate(45deg)
}

0 个答案:

没有答案