HTML and CSS Reference
In-Depth Information
Understanding CSS and Pixel Dimensions
The CSS dimensions and pixel dimensions of the page don't have to be the same, however. You can set the
CSS width and height (which determines the size of the element on the page) completely independent of the
pixel width and height. To make this clear, Listing 15-1 shows some code that puts a random colored, 1-pixel
rectangle at every pixel position of each of four different pixel-sized Canvas elements. All canvas elements are
set—via a CSS <style> tag—to 200 pixels wide by 200 pixels tall.
Listing 15-1: Examining CSS size versus pixel size
<script src='jquery.min.js'></script>
canvas { width: 200px; height: 200px; }
<canvas width="2" height="2"></canvas>
<canvas width="10" height="10"></canvas>
<canvas width="50" height="50"></canvas>
<canvas width="10" height="100"></canvas>
$("canvas").each(function() {
var ctx = this.getContext("2d");
for(var y=0,h=this.height;y<h;y++) {
for(var x=0,w=this.width;x<w;x++) {
var r = Math.floor(Math.random()*255),
g = Math.floor(Math.random()*255),
b = Math.floor(Math.random()*255);
ctx.fillStyle = "rgb(" + r + "," + g + "," + b + ")";
Figure 15-1 shows the result of running this code. Notice that although all canvas elements are set to the
same size on the page, they each have different pixel densities.
Search WWH ::

Custom Search