This tutorial shows you how to set a pixel in a canvas using javascript. The following tutorials will work towards making a graphics library so there is a little more code to this than there normally would be if you just wanted to set a pixel.
basic.js Left Click and select save file as to download
var Graphics = {
"Data":0,
"Width":0,
"Height":0,
"WidthInBytes":0,
"BytesPerPixel":4,
"Context":0,
"PutPixel": function(X, Y, Color) {
var Index = (Y * this.Data.width + X) * this.BytesPerPixel;
this.Data.data[Index+0] = Color[0];
this.Data.data[Index+1] = Color[1];
this.Data.data[Index+2] = Color[2];
this.Data.data[Index+3] = 0xFF;
},
"New": function(Context, Width, Height) {
this.Context = Context;
this.Width = Width;
this.WidthInBytes = Width * this.BytesPerPixel;
this.Height = Height;
this.Data = Context.createImageData(Width, Height);
return this.Data;
},
"Update": function() {
this.Context.putImageData(this.Data, 0, 0);
}
}
window.onload = function() {
var Width = 640;
var Height = 400;
var canvas = document.createElement("canvas");
var context = canvas.getContext("2d");
canvas.setAttribute("width", Width);
canvas.setAttribute("height", Height);
canvas.style.border = "solid 1px #CCC";
canvas.style.margin = "auto";
canvas.style.background = "#000";
document.body.appendChild(canvas);
document.body.style.textAlign = 'center';
Graphics.New(context, Width, Height);
Graphics.PutPixel(320, 200, [0x66, 0x99, 0xCC]);
Graphics.PutPixel(322, 201, [0x66, 0x99, 0xCC]);
Graphics.PutPixel(321, 202, [0x66, 0x99, 0xCC]);
Graphics.PutPixel(318, 199, [0x66, 0x99, 0xCC]);
Graphics.PutPixel(319, 198, [0x66, 0x99, 0xCC]);
Graphics.Update();
}
basic.htm Left Click and select save file as to download
<!DOCTYPE html>
<html>
<head>
<title>Future Programmer</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<script src="basic.js" type="text/javascript"></script>
</head>
<body>
</body>
</html>