Question

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>
Was it helpful?

Solution

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 :-)

OTHER TIPS

<canvas> is a bitmap "canvas", just think of it as a plain <img> for JavaScript to draw pixels. You cannot make it "responsive" just like you cannot make things on a image responsive w/o replacing the image.

That said, I did implemented a experimental feature that use a <div> as a "canvas" and draw the text with <span>s. They are still absolute positioned, but if you want to write additional JavaScript to move them around when the window is resized, you might be able achieve the responsive effect you want.

Good luck!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top