1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
|
(function($){
var ID = 0;
$.fn.jGraph=function(options){
var test=0;
// Defaults
var defaults = {
'width': 600,
'height': 250,
'abscissa': [-100, 100],
'ordered': [-50, +50]
};
var params = $.extend(defaults, options);
return this.each(function(){
$(this).attr('id', 'j$(this)'+(++ID));
this.stepX, this.stepY;
this.click = false;
this.abscissa = params.abscissa;
this.ordered = params.ordered;
var ctx = this.getContext('2d');
this.width = params.width;
this.height = params.height;
// css canvas
$(this).css({
'border': '1px solid black',
});
// Get mouse's coords
this.mouseCoords = function(e){
var x = e.clientX - this.offsetLeft;
var y = e.clientY - this.offsetTop;
console.log(x+' '+y);
return [x, y];
}
this.drawLines = function(){
console.log('ok');
// Step for the points
this.pointsX = this.abscissa[1]-this.abscissa[0];
this.pointsY = this.ordered[1]-this.ordered[0];
this.stepX = Math.round(params.width/this.pointsX);
this.stepY = params.height/this.pointsY;
// Ordered
ctx.strokeStyle='#383838';
ctx.lineWidth='1px';
ctx.beginPath();
ctx.moveTo(-(this.abscissa[0])*this.stepX, params.height);
ctx.lineTo(-(this.abscissa[0])*this.stepX, 0);
ctx.stroke();
// Ordered
ctx.strokeStyle='#383838';
ctx.lineWidth='1px';
ctx.beginPath();
ctx.moveTo(0, this.ordered[1]*this.stepY);
ctx.lineTo(params.width, this.ordered[1]*this.stepY);
ctx.stroke();
// Abcissa's points
for(i=-this.pointsX/10; i>=this.abscissa[0]-this.pointsX/10; i-= this.pointsX/10){
ctx.strokeStyle='#383838';
ctx.lineWidth='1px';
ctx.beginPath();
ctx.moveTo(Math.abs(this.abscissa[0]*this.stepX)+(i*this.stepX), this.ordered[1]*this.stepY+3);
ctx.lineTo(Math.abs(this.abscissa[0]*this.stepX)+(i*this.stepX), this.ordered[1]*this.stepY-3);
ctx.fillText(Math.round(i), Math.abs(this.abscissa[0]*this.stepX)+(i*this.stepX)-5, this.ordered[1]*this.stepY-4);
ctx.stroke();
}
}
this.draw = function(){
ctx.clearRect(0,0,params.width, params.height)
this.drawLines();
}
// Move $(this)
$(this).mousedown(function(e){
this.click = true;
clickCoords = this.mouseCoords(e);
});
$(this).mouseup(function(){
this.click = false;
});
$(this).mousemove(function(e){
if(this.click){
moveCoords = this.mouseCoords(e);
this.x = moveCoords[0]-clickCoords[0];
this.y = moveCoords[1]-clickCoords[1];
this.abscissa[0] -= this.x/this.stepX;
this.abscissa[1] -= this.x/this.stepX;
this.ordered[0] += this.y/this.stepY;
this.ordered[1] += this.y/this.stepY;
clickCoords = moveCoords;
console.log(this.x+' '+this.y);
this.draw();
}
});
this.draw();
});
};
})(jQuery); |
Partager