With wordcloud2.js you can create beautiful and easy wordclouds on canvas-elements. I don't really have problems with this script, actually only with the canvas-element in general: I'd like to have a responsive width (in this case relating to the browser-width).
It shows the correct width (100%), but the canvas is just upscaled and the "image" is distorted. If I save the "png" it has the old/basic resolution given by the script.
How to fix it?
<!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>
I got it! Sourround the canvas with a <div> element, which is 100% wide and has the id "sourrounding_div".
<div id="sourrounding_div" style="width:100%;height:500px">
<canvas id="canvas_cloud"></canvas>
</div>
In the <script> add before the var options:
var div = document.getElementById("sourrounding_div");
var canvas = document.getElementById("canvas_cloud");
canvas.height = div.offsetHeight;
canvas.width = div.offsetWidth;
That's all :-)