Skip to content

Instantly share code, notes, and snippets.

@reidev275
Last active December 12, 2015 08:08
Show Gist options
  • Save reidev275/4741529 to your computer and use it in GitHub Desktop.
Save reidev275/4741529 to your computer and use it in GitHub Desktop.
given <canvas id="canvas"></canvas> allow the user to draw on the canvas
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<canvas id="canvas" style="border: 1px solid black;"></canvas>
<p>
<button id="Clear">Clear</button>
<button id="Penups">Penups</button>
<button id="Points">Points</button>
</p>
</body>
<script>
var penTool = new PenTool('#canvas');
var topazTool = new TopazTool('#canvas');
$("#Clear").click(function () {
penTool.Clear();
topazTool.Clear();
});
$("#Penups").click(function() {
alert(topazTool.Penups().length);
});
$("#Points").click(function() {
alert(topazTool.Points().length);
});
</script>
</html>
var DT = (function(dt, $) {
dt.PenTool = function(id) {
var canvas = $(id);
var context = canvas[0].getContext("2d");
var isMouseDown = false;
canvas.mousedown(function (e) {
isMouseDown = true;
context.moveTo(e.offsetX, e.offsetY);
}).mouseup(function() {
isMouseDown = false;
}).mousemove(function(e) {
if (isMouseDown) {
context.lineTo(e.offsetX, e.offsetY);
context.stroke();
}
});
this.Clear = function() {
context.clearRect(0, 0, canvas.width(), canvas.height());
context.beginPath();
};
};
}) (DT || {}, jQuery);
var DT = (function(dt, $) {
dt.TopazTool = function(id) {
var canvas = $(id);
var isMouseDown = false;
var points = [];
var penups = [];
canvas.mousedown(function (e) {
isMouseDown = true;
points.push({ X: e.offsetX, Y: e.offsetY });
}).mouseup(function() {
isMouseDown = false;
penups.push(points.length);
}).mousemove(function(e) {
if (isMouseDown) {
points.push({ X: e.offsetX, Y: e.offsetY });
}
});
this.Clear = function() {
points = [];
penups = [];
};
this.Points = function() {
return points;
}
this.Penups = function() {
return penups;
}
};
}) (DT || {}, jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment