domingo, 24 de marzo de 2013

Drag and Drop Canvas

Antes que nada, el código no es mío, solo quiero aportarlo a mi blog por se simple y bello, el link a la web del autor se encuentra en Referencias.



<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>Canvas Drag and Drop Test</title>
 
 <script type="text/javascript">

 var canvas;
 var ctx;
 var x = 75;
 var y = 50;
 var WIDTH = 400;
 var HEIGHT = 300;
 var dragok = false;
 
 function rect(x,y,w,h) {
  ctx.beginPath();
  ctx.rect(x,y,w,h);
  ctx.closePath();
  ctx.fill();
 }
 
 function clear() {
  ctx.clearRect(0, 0, WIDTH, HEIGHT);
 }
 
 function init() {
  canvas = document.getElementById("canvas");
  ctx = canvas.getContext("2d");
  return setInterval(draw, 10);
 }
 
 function draw() {
  clear();
  ctx.fillStyle = "#FAF7F8";
  rect(0,0,WIDTH,HEIGHT);
  ctx.fillStyle = "#444444";
  rect(x - 15, y - 15, 30, 30);
 }
 
 function myMove(e){
  if (dragok){
   x = e.pageX - canvas.offsetLeft;
   y = e.pageY - canvas.offsetTop;
  }
 }
 
 function myDown(e){
  if (e.pageX < x + 15 + canvas.offsetLeft && e.pageX > x - 15 +
  canvas.offsetLeft && e.pageY < y + 15 + canvas.offsetTop &&
  e.pageY > y -15 + canvas.offsetTop){
   x = e.pageX - canvas.offsetLeft;
   y = e.pageY - canvas.offsetTop;
   dragok = true;
   canvas.onmousemove = myMove;
  }
 }
 
 function myUp(){
  dragok = false;
  canvas.onmousemove = null;
 }
 
 function here()
 {
  init();
  canvas.onmousedown = myDown;
  canvas.onmouseup = myUp;
 }
 </script>

</head>
 <body onLoad="here();">

 <canvas id="canvas" width="400" height="300">
  This text is displayed if your browser does not support HTML5 Canvas.
 </canvas>

 </body>
</html>



Así se vería si copias y pegas el codigo en un archivo html:




This text is displayed if your browser does not support HTML5 Canvas.

Referencias