使用wordcloud2.js(canvas html5元素)的响应宽度

Seb*_*ian 3 word-cloud html5-canvas responsive-design

使用wordcloud2.js,您可以在canvas-elements上创建漂亮且简单的wordcloud .我真的没有这个脚本的问题,实际上只有canvas-element一般:我想有一个响应宽度(在这种情况下与浏览器宽度有关).

它显示正确的宽度(100%),但画布只是放大,"图像"失真.如果我保存"png",它具有脚本给出的旧/基本分辨率.

怎么解决?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>canvas</title>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<script src="js/wordcloud2.js"></script>

<style type="text/css">    
#canvas_cloud{
width: 100%;
height:500px;
}
</style>

</head>

<body>

<canvas id="canvas_cloud"></canvas>

<script>

var options = 
{
  list : [ 
  ["Pear", "9"],
  ["Grape", "3"],
  ["Pineapple", "8"], 
  ["Apple", "5"]
  ],
  gridSize: Math.round(16 * document.getElementById('canvas_cloud').offsetWidth / 1024),
  weightFactor: function (size) {
    return Math.pow(size, 1.9) * document.getElementById('canvas_cloud').offsetWidth / 1024;
  }
}

WordCloud(document.getElementById('canvas_cloud'), options); 

</script>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

Seb*_*ian 9

我知道了!使用< div >元素对画布进行环绕,该元素为100%宽,ID为"sourrounding_div".

<div id="sourrounding_div" style="width:100%;height:500px">
<canvas id="canvas_cloud"></canvas>
</div>
Run Code Online (Sandbox Code Playgroud)

var 脚本选项之前的< script >中添加:

var div = document.getElementById("sourrounding_div");

var canvas = document.getElementById("canvas_cloud");

canvas.height = div.offsetHeight;

canvas.width  = div.offsetWidth;
Run Code Online (Sandbox Code Playgroud)

就这样 :-)