为什么 canvas 中的词云是模糊的?

Why the wordcloud in the canvas is blurry?

这是我的问题代码:

$(document).ready(render)


function render() {

  wl = [['hello', 12], ['dear', 10], ['a', 9], ['Joe', 5], ['8', 2]];

  $canvas = $('.wordcloud-canvas');
  options = {
    list           : wl,
    fontFamily     : 'Times, serif',
    weightFactor   : 2,
    color          : '#f02222',
    rotateRatio    : 0,
    rotationSteps  : 0,
    shuffle        : false,
    backgroundColor: 'white',
    drawOutOfBound : false,
    gridSize       : 32
  };
    
  window.WordCloud($canvas[0], options);
  
}
.wordcloud-view {
  display: block;
  margin: 01px 0;
    width: 100%;
    height: 100%;
}
.wordcloud-container {
  border: 1px blue solid;
  padding: 2px;
  width: 600px;
  height: 300px;
  margin: 0px;
}

.wordcloud-canvas {
  width: 600px;
  height: 300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/wordcloud2.js/1.0.6/wordcloud2.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wordcloud-view">
  <div class="wordcloud-container">
   <canvas id="wordcloud-canvas" class="wordcloud-canvas"></canvas>
   <div class="user-input"></div>
  <div></div>
</div></div>

不知何故输出非常模糊:

哪些因素使此处的输出变得模糊?

我正在使用wordcloud2.js生成词云。

我试过增加网格大小,但没有用。我想我在这里不知所措,因为我不明白 options 如何与 canvas 一起工作。

你也可以在这个代码笔中找到上面的代码:https://codepen.io/kongakong/pen/jaEMXG

在元素中添加width="600"height="300"(或者在渲染词云之前用JS设置-$canvas.attr('width', '600').attr('height', '300'))。

这与仅在CSS中设置不同,详情在这里:whosebug.com/a/43364730/3776299

$(document).ready(render);


function render() {
  var wl = [['hello', 12], ['dear', 10], ['a', 9], ['Joe', 5], ['8', 2]];

  var $canvas = $('.wordcloud-canvas');
  // this line is the only change from your snippet:
  $canvas.attr('width', '600').attr('height', '300');
  var options = {
    list           : wl,
    fontFamily     : 'Times, serif',
    weightFactor   : 2,
    color          : '#f02222',
    rotateRatio    : 0,
    rotationSteps  : 0,
    shuffle        : false,
    backgroundColor: 'white',
    drawOutOfBound : false,
    gridSize       : 32
  };
    
  window.WordCloud($canvas[0], options);
  
}
.wordcloud-canvas {
  width: 600px;
  height: 300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/wordcloud2.js/1.0.6/wordcloud2.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="wordcloud-canvas" class="wordcloud-canvas"></canvas>

这当然会使单词有点小,因为您的 options 中的 weightFactor 很小。 6-7 左右的值非常适合 600x300 尺寸。您也可以根据 canvas 大小和字重动态计算因子,例如:

weightFactor: function(size) {
    return Math.pow(size, 2.3) * $canvas.width() / 1024;
},

[从 wordcloud2 website("Configuration" 选项卡)获取和调整]