Skip to content

Instantly share code, notes, and snippets.

@willmcneilly
Created December 21, 2014 14:02
Show Gist options
  • Save willmcneilly/737332bf6c69e50f04a7 to your computer and use it in GitHub Desktop.
Save willmcneilly/737332bf6c69e50f04a7 to your computer and use it in GitHub Desktop.
A collection of useful canvas methods
var BasicCanvas = (function() {
return {
init: function() {
this.canvas = document.getElementById('canvas');
this.ctx = this.canvas.getContext('2d');
this.setSize(window.innerWidth, window.innerHeight);
},
setSize: function(x, y) {
this.width = this.canvas.width = x;
this.height = this.canvas.height = y;
},
clear: function(color) {
if(color) {
this.ctx.fillStyle = color;
this.ctx.fillRect(0, 0, this.width, this.height);
} else {
this.clearRect(0, 0, this.width, this.height);
}
},
getImage: function() {
var newWindow = window.open('', "Image"),
src = this.canvas.toDataURL("image/png");
newWindow.document.write('<img src="'+ src +'" />');
},
degToRad: function(degrees) {
return degrees * (Math.PI/180);
},
radToDeg: function(radians) {
return radians * (180/Math.PI);
},
randomiseNum: function(num, tolerance) {
var toleranceRange;
if(num > 0) {
toleranceRange = (tolerance * num) / 100;
} else {
return 0;
}
return (num + toleranceRange) + ((toleranceRange * 2) * Math.random());
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment