Install this theme
Draw rectangles with canvas tag in html5

So far I am loving what html5 has to offer for web and mobile applications. There’s some amazing stuff that can be done with mouse events and the 2d drawing API. This is a simple demo for creating filled black rectangles on a canvas. I am hoping to use this as a building construct in a much bigger project.

canvas.js

var rect;
var canvas;
var context;
var dragging;

function Point(x, y) {
	this.x = x;
	this.y = y;
}

function Size(width, height) {
	this.width = width;
	this.height = height;
}

function Rectangle(start, size) {
	this.start = start;
	this.size = size;
}

function init() {
	canvas = document.getElementById("canvas");
	context = canvas.getContext("2d");

	canvas.addEventListener("mousedown", startDragging, false);
	canvas.addEventListener("mouseup", stopDragging, false);
	canvas.addEventListener("mousemove", moved, false);

	var start = new Point(0, 0);
	var size = new Size(0, 0);
	rect = new Rectangle(start, size);
}

function startDragging(event) {
	dragging = true;

	// initialize start point
	rect.start.x = event.pageX;
	rect.start.y = event.pageY;

	// initialize size
	rect.size.width = 0;
	rect.size.height = 0;
}

function stopDragging(event) {
	dragging = false;
}

function moved(event) {
	if(!dragging) return;

	clearRect(rect);
	rect.size.width = event.pageX - rect.start.x;
	rect.size.height = event.pageY - rect.start.y;
	drawRect(rect);
}

function clearRect(rect) {
	context.clearRect(rect.start.x, rect.start.y, rect.size.width, rect.size.height);
}

function drawRect(rect) {
	context.fillRect(rect.start.x, rect.start.y, rect.size.width, rect.size.height);
}

And a html file to play along:

canvas.html

<html>
<head>
<script src="canvas.js"></script>
<style type="text/css">
canvas {
	background-color: #CCC;
}
body {
	margin: 0;
}
</style>
</head>

<body onload="init()">
<canvas id="canvas" width="1200" height="550"></canvas>
</body>

</html>
 
  1. vombat posted this
blog comments powered by Disqus