1 /** 2 * Canvas object 3 * @param {Number} w 4 * @param {Number} h 5 * @constructor 6 */ 7 function CP_Canvas(w, h) { 8 this.canvas = document.createElement('canvas'); 9 this.ctx = this.canvas.getContext('2d'); 10 this.w = w; 11 this.h = h; 12 this.x = 0; 13 this.y = 0; 14 this.touch = false; 15 this.top = 0; 16 this.left = 0; 17 this.scale = 1; 18 this.ratio = 1; 19 } 20 21 /** 22 * Abstract event handler 23 * @param {String} e 24 */ 25 CP_Canvas.prototype.on = function(e) {}; 26 27 /** 28 * Bind canvas events 29 * @returns {CP_Canvas} 30 */ 31 CP_Canvas.prototype.bind = function() { 32 var self = this; 33 this.canvas.addEventListener('touchstart', function(e) { 34 e.preventDefault(); 35 self.x = (e.touches[0].pageX - self.left) / self.scale; 36 self.y = (e.touches[0].pageY - self.top) / self.scale; 37 self.touch = true; 38 self.on('start'); 39 }); 40 this.canvas.addEventListener('mousedown', function(e) { 41 e.preventDefault(); 42 self.x = (e.clientX - self.left) / self.scale; 43 self.y = (e.clientY - self.top) / self.scale; 44 self.touch = true; 45 self.on('start'); 46 }); 47 this.canvas.addEventListener('touchmove', function(e) { 48 e.preventDefault(); 49 self.x = (e.touches[0].pageX - self.left) / self.scale; 50 self.y = (e.touches[0].pageY - self.top) / self.scale; 51 self.on('move'); 52 }); 53 this.canvas.addEventListener('mousemove', function(e) { 54 e.preventDefault(); 55 self.x = (e.clientX - self.left) / self.scale; 56 self.y = (e.clientY - self.top) / self.scale; 57 self.on('move'); 58 }); 59 this.canvas.addEventListener('touchend', function(e) { 60 e.preventDefault(); 61 self.on('end'); 62 self.touch = false; 63 }); 64 this.canvas.addEventListener('mouseup', function(e) { 65 e.preventDefault(); 66 self.on('end'); 67 self.touch = false; 68 }); 69 return this; 70 }; 71 72 /** 73 * Resize the canvas object 74 * @returns {CP_Canvas} 75 */ 76 CP_Canvas.prototype.resize = function() { 77 var width = document.body.clientWidth, 78 height = document.body.clientHeight, 79 ratio = window.devicePixelRatio || 1, 80 scale = width / this.w > height / this.h ? height / this.h : width / this.w; 81 this.left = Math.round((width - this.w * scale) / 2); 82 this.top = Math.round((height - this.h * scale) / 2); 83 if (width / height > this.w / this.h) { 84 this.canvas.style.left = this.left + 'px'; 85 this.canvas.style.top = '0px'; 86 } else { 87 this.canvas.style.top = this.top + 'px'; 88 this.canvas.style.left = '0px'; 89 } 90 this.canvas.width = Math.round(this.w * scale * ratio); 91 this.canvas.height = Math.round(this.h * scale * ratio); 92 this.canvas.style.width = Math.round(this.w * scale) + 'px'; 93 this.canvas.style.height = Math.round(this.h * scale) + 'px'; 94 this.ctx.scale(scale * ratio, scale * ratio); 95 this.scale = scale; 96 this.ratio = ratio; 97 return this; 98 }; 99