Keyboard Controlled Pixel Drawing

anilashanbhag 1 Tallied Votes 699 Views Share

The script is used in my newest chrome app

Site:
http://codestrix.co.cc/pixels/

The above script is a good to get stated with HTML5 canvas.
Much of it is named so as to be self explanatory but any doubts you are more than welcome to post it here.

var currentx = 350;
	var currenty = 350;
	var ltArrow = 37;
	var upArrow = 38;
	var rtArrow = 39;
	var dwArrow = 40;
	var size = 50;

	
function keyHit(evt) {
	var oCanvas = document.getElementById('oCanvas');
	var oCtx = oCanvas.getContext('2d');
	var thisKey;
	if (evt) {
		thisKey = evt.which;
	}
	else {
		thisKey = window.event.keyCode;
	}
	switch(thisKey){
		case ltArrow:
			currentx -= size;
			if(currentx<0){currentx = 0;}
			oCtx.fillRect(currentx, currenty, size, size);
			break;
		case rtArrow:
			currentx += size;
			if(currentx>800-size){currentx = 800-size;}
			oCtx.fillRect(currentx, currenty, size, size);
			break;
		case upArrow:
			currenty -= size;
			if(currenty<0){currenty = 0;}
			oCtx.fillRect(currentx, currenty, size, size);
			break;
		case dwArrow:
			currenty += size;
			if(currenty>800-size){currenty=800-size;}
			oCtx.fillRect(currentx, currenty, size, size);
			break;
		default:
			break;
	}
return False;
}

function resetSize(){
	var newLoc = document.getElementById("size");
	newLoc.blur();
	var newSize = newLoc.options[newLoc.selectedIndex].value;
	size = parseInt(newSize);
}

function resetColor(){
	var newLoca = document.getElementById("color");
	newLoca.blur();
	var newColor = newLoca.options[newLoca.selectedIndex].value;
	var oCanvas = document.getElementById('oCanvas');
	var oCtx = oCanvas.getContext('2d');
	oCtx.fillStyle = newColor;
}
	
window.onload = init;

function init(){
	var oCanvas = document.getElementById('oCanvas');
	var iWidth = oCanvas.width;
	var iHeight = oCanvas.height;
	var oCtx = oCanvas.getContext('2d');
	var iWidth = oCanvas.width;
	var iHeight = oCanvas.height;
	oCtx.fillStyle = "rgb(0,0,255)";
	oCtx.fillRect(currentx,currenty, 50, 50);
	document.onkeydown = keyHit;
	document.getElementById("size").selectedIndex = 4;
	document.getElementById("size").onchange = resetSize;
	document.getElementById("color").selectedIndex = 3;
	document.getElementById("color").onchange = resetColor;
	
	function showDownloadText() {
		document.getElementById("buttoncontainer").style.display = "none";
		document.getElementById("textdownload").style.display = "block";
	}

	function hideDownloadText() {
		document.getElementById("buttoncontainer").style.display = "block";
		document.getElementById("textdownload").style.display = "none";
	}

	function convertCanvas(strType) {
		if (strType == "PNG")
			var oImg = Canvas2Image.saveAsPNG(oCanvas, true);
		if (strType == "BMP")
			var oImg = Canvas2Image.saveAsBMP(oCanvas, true);
		if (strType == "JPEG")
			var oImg = Canvas2Image.saveAsJPEG(oCanvas, true);

		if (!oImg) {
			alert("Sorry, this browser is not capable of saving " + strType + " files!");
			return false;
		}

		oImg.id = "canvasimage";

		oImg.style.border = oCanvas.style.border;
		oCanvas.parentNode.replaceChild(oImg, oCanvas);

		showDownloadText();
	}

	function saveCanvas(pCanvas, strType) {
		var bRes = false;
		if (strType == "PNG")
			bRes = Canvas2Image.saveAsPNG(oCanvas);
		if (strType == "BMP")
			bRes = Canvas2Image.saveAsBMP(oCanvas);
		if (strType == "JPEG")
			bRes = Canvas2Image.saveAsJPEG(oCanvas);

		if (!bRes) {
			alert("Sorry, this browser is not capable of saving " + strType + " files!");
			return false;
		}
	}

	//document.getElementById("savepngbtn").onclick = function() {saveCanvas(oCanvas, "PNG");	}
	//document.getElementById("savebmpbtn").onclick = function() {saveCanvas(oCanvas, "BMP");	}
	//document.getElementById("savejpegbtn").onclick = function() {saveCanvas(oCanvas, "JPEG");}

	document.getElementById("convertpngbtn").onclick = function() {convertCanvas("PNG");}
	//document.getElementById("convertbmpbtn").onclick = function() {convertCanvas("BMP");}
	document.getElementById("convertjpegbtn").onclick = function() {convertCanvas("JPEG");}

	document.getElementById("resetbtn").onclick = function() {var oImg = document.getElementById("canvasimage");oImg.parentNode.replaceChild(oCanvas, oImg);
		hideDownloadText();	}
	}

Dani AI

Generated

Nice starter, . Good point, — a visible cursor/tracer helps a lot. A few focused, practical improvements will make the sketch more reliable and easier to extend:

  • Make the canvas focusable and attach keyboard handling to it so arrow keys don't scroll the page. Use modern key names (e.key === 'ArrowLeft') and e.preventDefault() rather than relying on returning an uppercase False.
  • Support continuous movement while a key is held by tracking key state and driving motion with requestAnimationFrame.
  • Avoid redeclaring variables, use let/const, always pass a radix to parseInt(value, 10), and scale the canvas for high-DPI displays to avoid blurring.

Example: keyboard focus + continuous movement pattern you can drop in (adapt sizes/initials to your code):

const canvas = document.getElementById('oCanvas');
canvas.tabIndex = 0;               // allow keyboard focus
canvas.style.outline = '2px solid rgba(0,0,0,0.15)';
canvas.focus();

const ctx = canvas.getContext('2d');
const keys = {};
let x = 350, y = 350, size = 50;

canvas.addEventListener('keydown', e => {
  if (e.key.startsWith('Arrow')) { e.preventDefault(); keys[e.key] = true; }
});
canvas.addEventListener('keyup',   e => { if (e.key.startsWith('Arrow')) keys[e.key] = false; });

function clamp(v, a, b){ return Math.max(a, Math.min(b, v)); }

function frame(){
  if (keys['ArrowLeft'])  x -= size;
  if (keys['ArrowRight']) x += size;
  if (keys['ArrowUp'])    y -= size;
  if (keys['ArrowDown'])  y += size;
  x = clamp(x, 0, canvas.width - size);
  y = clamp(y, 0, canvas.height - size);
  ctx.clearRect(0,0,canvas.width,canvas.height);
  ctx.fillRect(x,y,size,size);
  requestAnimationFrame(frame);
}
requestAnimationFrame(frame);

Two quick bonus tips: scale the canvas by devicePixelRatio so squares are crisp on Retina screens, and use canvas.toBlob(...) (or toDataURL) to export images rather than relying on third-party helpers. Also be careful not to "swallow" accessibility keys — allow Tab/Shift-Tab to move focus out when needed and show a clear focus indicator so keyboard users know where they are.

Luckychap 68 Posting Pro in Training

Nice job. It would be better if there is indication of current cursor position on the canvas. Something different from background color.

anilashanbhag 0 Junior Poster in Training

I did add a tracer to keep track of the current position but yes working on adding current position.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.