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
| <!DOCTYPE html>
<html>
<head>
<title>Test canvas</title>
<meta charset="utf-8" />
</head>
<body onload="draw()">
<canvas id="canvas" width="400px" height="400px" style="border: 1px solid #999;"></canvas>
<script type="text/javascript">
//Initialisation canvas
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
function draw() {
ctx.fillStyle = 'rgb(100,100,100)';
ctx.fillRect(50,50,100,100);
}
//Drag and drop
var DragHandler = {
//Privé
_oElem : null,
_oX : 50,
_oY : 50,
//Public
attach : function(oElem) {
oElem.onmousedown = DragHandler._dragBegin;
// callbacks
oElem.dragBegin = new Function();
oElem.drag = new Function();
oElem.dragEnd = new Function();
return oElem;
},
//Privé
_dragBegin : function(e) {
var oElem = DragHandler._oElem = this;
e = e ? e : window.event;
var x = e.clientX - oElem.offsetLeft;
var y = e.clientY - oElem.offsetTop;
oElem.dragBegin(oElem, x, y);
if (x >= DragHandler._oX && x <= (DragHandler._oX + 100) && y >= DragHandler._oY && y <= (DragHandler._oY + 100)) {
oElem.style.cursor = 'pointer';
document.onmousemove = DragHandler._drag;
document.onmouseup = DragHandler._dragEnd;
}
return false;
},
//Privé
_drag : function(e) {
var oElem = DragHandler._oElem;
e = e ? e : window.event;
var x = e.clientX - oElem.offsetLeft;
var y = e.clientY - oElem.offsetTop;
/*if (x > DragHandler._oX) {
x = x - (x - DragHandler._oX);
}
if (y > DragHandler._oY) {
y = y - (y - DragHandler._oY);
}*/
oElem.drag(oElem, x, y);
ctx.clearRect(0, 0, 400, 400);
ctx.fillStyle = 'rgb(100,200,50)';
ctx.fillRect(x,y,100,100);
DragHandler._oX = x;
DragHandler._oY = y;
return false;
},
//Privé
_dragEnd : function() {
var oElem = DragHandler._oElem;
var x = x;
var y = y;
oElem.dragEnd(oElem, x, y);
oElem.style.cursor = 'default';
document.onmousemove = null;
document.onmouseup = null;
DragHandler._oElem = null;
}
}
//Instanciation
var d = DragHandler.attach(document.getElementById('canvas'));
</script>
</body>
</html> |
Partager