Pixelated images
by Riham
HTML
<body>
<p>
<button onclick="parse();"><</button>
<button onclick="parse();">></button>
<button onclick="parse();">/\</button>
<button onclick="parse();">\/</button>
<button onclick="parse();">+</button>
<button onclick="parse();">-</button>
</p>
<p>
<canvas id="myCanvas" width="402" height="402">Your browser does not have support for Canvas. You should see: <span style="display:block;width:50px;height:50px;background:#f77"> </span>
</canvas>
</p>
</body>
CSS
.grid {
margin:1em auto;
border-collapse:collapse
}
.grid td {
cursor:pointer;
width:30px;
height:30px;
border:1px solid #ccc;
text-align:center;
font-family:sans-serif;
font-size:9px;
}
.grid td.clicked {
background-color:black;
font-weight:bold;
color:white;
}
JavaScript
var width = 20;
//grid width and height
var bw = 400;
var bh = 400;
//padding around grid
var p = 0;
//size of canvas
var cw = bw + (p * 2) + 1;
var ch = bh + (p * 2) + 1;
// Create a new image.
var img = new Image();
function drawSquare()
{
// Get the canvas element.
var elem = document.getElementById('myCanvas');
if (!elem || !elem.getContext) {
return;
}
// Get the canvas 2d context.
var context = elem.getContext('2d');
if (!context || !context.putImageData) {
return;
}
//var grid = drawGrid(width, width);
var imgd = false,
w = 40,
h = 40,
x = 0,
y = 0;
// Not all browsers implement createImageData. On such browsers we obtain the
// ImageData object using the getImageData method. The worst-case scenario is
// to create an object *similar* to the ImageData object and hope for the best
// luck.
if (context.createImageData) {
imgd = context.createImageData(w, h);
} else if (context.getImageData) {
imgd = context.getImageData(0, 0, w, h);
} else {
imgd = {
'width': w,
'height': h,
'data': new Array(w * h * 4)
};
}
var pix = imgd.data;
// Loop over each pixel.
for (var i = 0, n = pix.length; i < n; i += 4) {
pix[i] = 255; // the red channel
pix[i + 3] = 127; // the alpha channel
}
// Draw the ImageData object.
context.putImageData(imgd, x, y);
}
window.addEventListener('load', function () {
drawSquare();
// Get the canvas element.
var elem = document.getElementById('myCanvas');
if (!elem || !elem.getContext) {
return;
}
// Get the canvas 2d context.
var context = elem.getContext('2d');
if (!context || !context.putImageData) {
return;
}
//var grid = drawGrid(width, width);
for (var x = 0; x <= bw; x += 40) {
context.moveTo(0.5 + x + p, p);
...