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 112 113 114 115 116 117 118 119 120
|
//HTML
<canvas id="circle" width="200" height="200"></canvas>
//JAVASCRIPT
/** Initialisation des variables et l'objet canvas **/
var canvas = document.id('circle'),
context = canvas.getContext('2d'),
Circle,
ball;
/** création de la class circle attributes & events **/
Circle = new Class({
Implements: [Options, Events],
initialize: function (options) {
this.setOptions(options);
this.draw().attach();
},
attach: function () {
this.addEvent('change', this.draw);
},
set: function (what, value) {
this.options[what] = value;
this.fireEvent('change');
return this;
},
get: function (what) {
return this.options[what];
},
draw: function () {
context.clearRect(this.options.x, this.options.y, this.options.radius * 2, this.options.radius * 2);
context.beginPath();
context.arc(this.options.x + this.options.radius, this.options.y + this.options.radius, this.options.radius, 0, 2 * Math.PI, false);
context.fillStyle = this.options.background;
context.fill();
return this;
},
getSize: function () {
return {
width: this.options.radius * 2,
height: this.options.radius * 2
}
},
getPosition: function () {
var position = {
x: this.get('x'),
y: this.get('y')
}
return position;
},
getColor: function(){
var style = {
background: this.get('background')
}
return style;
},
isMouseOver: function (x, y) {
var position = this.getPosition(),
size = this.getSize(),
radius = this.options.radius,
centerX = position.x + (size.width / 2),
centerY = position.y + (size.height / 2),
distanceX = x - centerX,
distanceY = y - centerY;
// console.log(x)
return Math.round(Math.sqrt(Math.pow(x - centerX, 2) + Math.pow(y - centerY, 2))) <= radius;
}
});
/** initialisation des attributs et events de l'object circles **/
ball = new Circle({
x: canvas.width / 2,
y: canvas.height / 2,
radius: 40,
background: 'red'
});
ball.addEvent('mouseenter', function () {
this.set('background', 'blue');
});
ball.addEvent('mouseleave', function () {
console.log(this.getColor().background)
var color = (color === ball.style) ? 'red' : 'yellow';
this.set('background', color);
});
canvas.addEvent('mousemove', function (e) {
var x = e.client.x,
y = e.client.y;
if (ball.isMouseOver(x, y)) {
if (!ball.mouseover) {
ball.fireEvent('mouseenter');
ball.mouseover = true;
}
} else if (ball.mouseover) {
ball.mouseover = false;
ball.fireEvent('mouseleave');
}
}); |
Partager