elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Usando Git para manipular el directorio de trabajo, el índice y commits (segunda parte)


+  Foro de elhacker.net
|-+  Programación
| |-+  Desarrollo Web (Moderador: #!drvy)
| | |-+  dibujar y borrar
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: dibujar y borrar  (Leído 3,052 veces)
bengy


Desconectado Desconectado

Mensajes: 501


mis virtudes y defectos son inseparables


Ver Perfil WWW
dibujar y borrar
« en: 15 Abril 2015, 18:28 pm »

como podria dibujar una linea en canvas  y luego borrarla cuando deje de apretar una tecla ?

 este es mi  codigo

ya puedo dibujar la linea pero cuando dejo de presionar la tecla deberia borrarse la linea dibujada


bueno pretendo hacer este juego
https://www.youtube.com/watch?v=WuuO7aOrTwo

ayuda please!!!
Código
  1.  
  2. // Variables globales
  3.  
  4.  
  5. function main()
  6. {
  7. window.addEventListener('keydown', dirigir, true);
  8. var canvas  = document.getElementById("canvas2D");
  9. var cWidth  = document.getElementById("canvas2D").width;
  10. var cheight = document.getElementById("canvas2D").height;
  11.   var context = canvas.getContext("2d");
  12.   var player={direction:39, posX:20, posY:20, ancho:10, alto:10};
  13. var enemigo={posX:200, posY:200, ancho:50, alto:50};
  14. var lineaDibujada={X1:20, Y1:20, X2:player.posX, Y2:player.posY};
  15. //context.fillRect(20,20,50,50);
  16. function init(){
  17. if(typeof game_loop!="undefined"){
  18. clearInterval(game_loop);
  19. }
  20. game_loop=setInterval(main,200);
  21. }
  22.  
  23. function dibujarLinea(X1,Y1,X2,Y2){
  24. context.save();
  25. context.moveTo(X1,Y1);
  26. context.lineTo(X2,Y2);
  27. context.strokeStyle = "#f00";
  28. context.stroke();
  29. context.restore();
  30. }
  31.  
  32.      function dirigir(evt) {
  33.  
  34.       if(evt.keyCode!=null){
  35.       switch(evt.keyCode){
  36. case 39:
  37. if(player.posX<cWidth-4){
  38.  
  39. player.posX+=2;
  40.  
  41. }
  42. break;
  43. case 37:
  44.  
  45. if(player.posX>-1){
  46. //dibujarLinea(player.posX,player.posY,player.posX-2,player.posY);
  47. player.posX-=2;
  48. }
  49. break;
  50. case 38:
  51. if(player.posY>-1){
  52. // dibujarLinea(player.posX,player.posY,player.posX,player.posY-2);
  53. player.posY -=2;
  54. }
  55. break;
  56. case 40:
  57.   if(player.posY<cheight-4){
  58.  // dibujarLinea(player.posX,player.posY,player.posX,player.posY+2);
  59.   player.posY+=2;
  60.   }
  61.  
  62. break;
  63. default:
  64. player.posX=player.posX;
  65. player.posY=player.posY;
  66.        }
  67.       }else{
  68.       context.restore();
  69.       //context.clearRect(0,0,cWidth,cheight);
  70.  
  71.       }
  72.  
  73.      }
  74.  
  75. function main(){
  76. moverEnemigo();
  77. setBackground();
  78. drawPlayer();
  79. dibujarLinea(lineaDibujada.posX1,lineaDibujada.posY1,player.posX,player.posY);
  80. drawEnemigo();
  81. }
  82. function moverEnemigo(){
  83. var aleatorio =Math.random();
  84. aleatorio =aleatorio*100;
  85. if(aleatorio<25){
  86. if(enemigo.posX<cWidth-20){
  87. enemigo.posX+=10;
  88. }else{
  89. enemigo.posX-=10;
  90. }
  91.  
  92. }
  93. if(aleatorio>=25&& aleatorio<45){
  94. if (enemigo.posX>20){
  95. enemigo.posX-=10;
  96. }else{
  97. enemigo.posX+=10;
  98. }
  99. }
  100. if(aleatorio>=45 && aleatorio<70){
  101. if(enemigo.posY>20){
  102. enemigo.posY-=10;
  103. }
  104. else{
  105. enemigo.posY+=10;
  106. }
  107. }
  108. if(aleatorio>=70 && aleatorio<=100){
  109. if(enemigo.posY<cheight-20){
  110.   enemigo.posY+=10;
  111. }else{
  112. enemigo.posY-=10;
  113. }
  114. }
  115.  
  116.  
  117. //para que se acerque al jugador e imponga miedo
  118.  
  119. }
  120. function setBackground(){
  121. context.save();
  122. context.fillStyle="white";
  123. context.fillRect(0,0,cWidth,cheight);
  124. context.strokeStyle="black";
  125. context.strokeRect(0,0,cWidth,cheight);
  126. context.restore();
  127. }
  128. setBackground();
  129. function drawPlayer(){
  130. context.save();
  131. context.fillStyle="blue";
  132. context.fillRect(player.posX,player.posY, player.ancho,player.alto);
  133. context.restore();
  134. }
  135. function drawEnemigo(){
  136. context.save();
  137. context.fillStyle="Red";
  138. context.fillRect(enemigo.posX,enemigo.posY, enemigo.ancho,enemigo.alto);
  139. context.restore();
  140. }
  141.  
  142. init();
  143. }
  144.  



Código
  1. <!DOCTYPE HTML>
  2. <script src="animatorStix.js"></script>
  3. <link rel="stylesheet" type="text/css" href="style.css">
  4. <title>GOGOGO</title>
  5. </head>
  6.  
  7. <body onload="main()">
  8. <h1> GOGOGO </h1>
  9. <canvas id="canvas2D" width="500" height="400">Navegador no soportado</canvas>
  10.  
  11.  
  12. </body>
  13.  
  14. </html>
  15.  

Mod: Tema modificado, colocadas etiquetas GeSHi para mejor visualización del código


« Última modificación: 18 Abril 2015, 05:45 am por engel lex » En línea

EFEX


Desconectado Desconectado

Mensajes: 1.171


"Dinero Facil"


Ver Perfil WWW
Re: dibujar y borrar
« Respuesta #1 en: 15 Abril 2015, 20:37 pm »

Fijate que estas abusando de .save() y .restore(), ademas de que a cada loop que haga se guarda el estado anterior en ms.

Podrias utilizar keyup para saber cuando se esta dejando de presionar el boton..

Código
  1. //Claro necesita ser pulido.. pero para que entiendas la idea..
  2. window.addEventListener('keyup', function(){
  3.   console.log('Se solto la tecla..');
  4.   context.restore();
  5. }, true);
  6.  

Otra idea seria crear diferentes layers.. por ejemplo 1 canvas para el cuadrado rojo, otro el cuadrado azul, otro la linea que este dibujando el cuadrado azul y por ultimo otros las diferentes lineas ya trazadas por el jugador..


En línea

bengy


Desconectado Desconectado

Mensajes: 501


mis virtudes y defectos son inseparables


Ver Perfil WWW
Re: dibujar y borrar
« Respuesta #2 en: 15 Abril 2015, 23:39 pm »

seria tan amable de explicarme un poquito mas


porfaaaa  alguna idea

para dibujar y luego que se borre!!!

« Última modificación: 15 Abril 2015, 23:43 pm por DeviiAC » En línea

Usuario Invitado


Desconectado Desconectado

Mensajes: 625



Ver Perfil
Re: dibujar y borrar
« Respuesta #3 en: 16 Abril 2015, 02:20 am »

Necesitas limpiar todo el canvas. Para ésto, debes de guardar todos los elementos dibujados. Al detectar que se ha soltado la tecla, se elimina el trazo reciente de la colección y se redibuja todo.

Código
  1. window.addEventListener('keyup', function(){
  2.    redrawAllStored();
  3. }, true);

Como todos tus elementos dibujados están guardados, redrawAllStored() los redibujaría.

Código
  1. function redrawStoredLines(){
  2.        ctx.clearRect(0,0,canvas.width,canvas.height);
  3.  
  4.        if(storedLines.length==0){ return; }
  5.  
  6.        // redibuja cada linea guardada
  7.        for(var i=0;i<storedLines.length;i++){
  8.            ctx.beginPath();
  9.            ctx.moveTo(storedLines[i].x1,storedLines[i].y1);
  10.            ctx.lineTo(storedLines[i].x2,storedLines[i].y2);
  11.            ctx.stroke();
  12.        }
  13.    }
« Última modificación: 16 Abril 2015, 17:37 pm por Gus Garsaky » En línea

"La vida es muy peligrosa. No por las personas que hacen el mal, si no por las que se sientan a ver lo que pasa." Albert Einstein
bengy


Desconectado Desconectado

Mensajes: 501


mis virtudes y defectos son inseparables


Ver Perfil WWW
Re: dibujar y borrar
« Respuesta #4 en: 18 Abril 2015, 00:00 am »

creo que se esta volviendo a dibujar la linea anterior cada vez,

lo que yo pretendo hacer es lo siguiente:

cuando deje de apretar la tecla 'x' se tendria que borrar la linea
si sigue apretando la tecla 'x' tendria que dibujarse continumente


Código:
// Variables globales
   

function main()
{
window.addEventListener('keydown', dirigir, true);
window.addEventListener('keypress',press,true);
window.addEventListener('keyup', soltarTeclado, true);
var canvas  = document.getElementById("canvas2D");
var cWidth  = document.getElementById("canvas2D").width;
var cheight = document.getElementById("canvas2D").height;
    var context = canvas.getContext("2d");
    var player={direction:39, posX:20, posY:20, ancho:10, alto:10};
var enemigo={posX:200, posY:200, ancho:50, alto:50};
var lineaDibujada={X1:20, Y1:20, X2:player.posX, Y2:player.posY};
//context.fillRect(20,20,50,50);
var f=0;
function init(){
if(typeof game_loop!="undefined"){
clearInterval(game_loop);
}
game_loop=setInterval(main,200);
}

  function dibujarLinea(X1,Y1,X2,Y2){
  context.moveTo(X1,Y1);
context.lineTo(X2,Y2);
context.strokeStyle = "#f00";
context.stroke();
  }
  function press(evt){
  if(evt.keyCode==120){
  //alert("ja");

  dibujarLinea(lineaDibujada.X2,player.posY,player.posX,player.posY);
  }
  }
  function soltarTeclado(evt){
  if(evt.keyCode==120){
  context.clearRect(0,0,cWidth,cheight);
  }
  }
      function dirigir(evt) {

     
        switch(evt.keyCode){
case 39:
if(f==0){
lineaDibujada.X2=player.posX;
f=f+1;
//alert("olo");
}

if(player.posX<cWidth-4){


player.posX+=2;

}
break;
case 37:

if(player.posX>-1){

//dibujarLinea(player.posX,player.posY,player.posX-2,player.posY);

player.posX-=2;
}
break;
case 38:
if(player.posY>-1){
// dibujarLinea(player.posX,player.posY,player.posX,player.posY-2);
player.posY -=2;
}
break;
case 40:
   if(player.posY<cheight-4){
  // dibujarLinea(player.posX,player.posY,player.posX,player.posY+2);
    player.posY+=2;
   }

break;
default:
player.posX=player.posX;
player.posY=player.posY;
lineaDibujada.posX1=player.posX;
lineaDibujada.posY1=player.posY;
        }
     

      }
   

function main(){
moverEnemigo();
setBackground();
drawPlayer();

drawEnemigo();
}
function moverEnemigo(){
var aleatorio =Math.random();
aleatorio =aleatorio*100;
if(aleatorio<20){
if(enemigo.posX<cWidth-20){
enemigo.posX+=10;
}else{
enemigo.posX-=10;
}

}
if(aleatorio>=20&& aleatorio<45){
if (enemigo.posX>20){
enemigo.posX-=10;
}else{
enemigo.posX+=10;
}
}
if(aleatorio>=45 && aleatorio<70){
if(enemigo.posY>20){
enemigo.posY-=10;
}
else{
enemigo.posY+=10;
}
}
if(aleatorio>=70 && aleatorio<=100){
if(enemigo.posY<cheight-20){
    enemigo.posY+=10;
}else{
enemigo.posY-=10;
}
}


//para que se acerque al jugador e imponga miedo

}
function setBackground(){
context.save();
context.fillStyle="white";
context.fillRect(0,0,cWidth,cheight);
context.strokeStyle="black";
context.strokeRect(0,0,cWidth,cheight);
context.restore();
}
setBackground();
function drawPlayer(){
context.save();
context.fillStyle="blue";
context.fillRect(player.posX,player.posY, player.ancho,player.alto);
context.restore();
}
function drawEnemigo(){
context.save();
context.fillStyle="Red";
context.fillRect(enemigo.posX,enemigo.posY, enemigo.ancho,enemigo.alto);
context.restore();
}

init();
}


En línea

EFEX


Desconectado Desconectado

Mensajes: 1.171


"Dinero Facil"


Ver Perfil WWW
Re: dibujar y borrar
« Respuesta #5 en: 21 Abril 2015, 01:35 am »

Ya dije que estas abusando de  .save() y .restore()... espero que lo entiendas..

Código
  1. // Variables globales
  2.  
  3.  
  4. function main(){
  5. window.addEventListener('keydown', dirigir, true);
  6. //Miestras tenga la tecla mantenida..
  7. window.addEventListener('keyup', keyup, true);
  8. var canvas  = document.getElementById("canvas2D");
  9. var cWidth  = document.getElementById("canvas2D").width;
  10. var cheight = document.getElementById("canvas2D").height;
  11. var context = canvas.getContext("2d");
  12. var player={direction:39, posX:0, posY:20, ancho:10, alto:10};
  13. var enemigo={posX:200, posY:200, ancho:50, alto:50};
  14. var lineaDibujada={X1:20, Y1:20, X2:player.posX, Y2:player.posY};
  15. //context.fillRect(20,20,50,50);
  16.  
  17. function init(){
  18. if(typeof game_loop!="undefined"){
  19. clearInterval(game_loop);
  20. }
  21. game_loop=setInterval(main,200);
  22. }
  23.  
  24. function dibujarLinea(X1,Y1,X2,Y2){
  25. //context.save(); No es necesario
  26. context.moveTo(X1,Y1);
  27. context.lineTo(X2,Y2);
  28. context.strokeStyle = "#f00";
  29. context.stroke();
  30. //context.restore(); No es necesario
  31. }
  32.  
  33. function keyup(){
  34. console.log('Se suelta la tecla...');
  35. //Mientras se presione la tecla mostrar la linea..
  36. context.restore();
  37. }
  38.  
  39. function dirigir(evt) {
  40. if(evt.keyCode!=null){
  41. switch(evt.keyCode){
  42. case 39:
  43. if(player.posX<cWidth-4){
  44. player.posX+=2;
  45. }
  46. break;
  47. case 37:
  48. if(player.posX>-1){
  49. player.posX-=2;
  50. }
  51. break;
  52. case 38:
  53. if(player.posY>-1){
  54. player.posY -=2;
  55. }
  56. break;
  57. case 40:
  58. if(player.posY<cheight-4){
  59. player.posY+=2;
  60. }
  61. break;
  62. default:
  63. player.posX=player.posX;
  64. player.posY=player.posY;
  65. }
  66. }
  67.  
  68. //Cuando se presiona una tecla es cuando dibujamos la linea
  69. dibujarLinea(lineaDibujada.posX1,lineaDibujada.posY1,player.posX,player.posY);
  70. //Guardamos la linea dibujada
  71. context.save();
  72. }
  73.  
  74. function main(){
  75. setBackground();
  76. //No lo necesitamos dentro del loop..
  77. //dibujarLinea(lineaDibujada.posX1,lineaDibujada.posY1,player.posX,player.posY);
  78. drawEnemigo();
  79. drawPlayer();
  80. moverEnemigo();
  81. }
  82.  
  83. function moverEnemigo(){
  84. var aleatorio =Math.random();
  85. aleatorio =aleatorio*100;
  86. if(aleatorio<25){
  87. if(enemigo.posX<cWidth-20){
  88. enemigo.posX+=10;
  89. }else{
  90. enemigo.posX-=10;
  91. }
  92.  
  93. }
  94. if(aleatorio>=25&& aleatorio<45){
  95. if (enemigo.posX>20){
  96. enemigo.posX-=10;
  97. }else{
  98. enemigo.posX+=10;
  99. }
  100. }
  101. if(aleatorio>=45 && aleatorio<70){
  102. if(enemigo.posY>20){
  103. enemigo.posY-=10;
  104. }
  105. else{
  106. enemigo.posY+=10;
  107. }
  108. }
  109. if(aleatorio>=70 && aleatorio<=100){
  110. if(enemigo.posY<cheight-20){
  111. enemigo.posY+=10;
  112. }else{
  113. enemigo.posY-=10;
  114. }
  115. }
  116. }
  117.  
  118. function setBackground(){
  119. // context.save();  No es necesario
  120. context.fillStyle="white";
  121. context.fillRect(0,0,cWidth,cheight);
  122. context.strokeStyle="black";
  123. context.strokeRect(0,0,cWidth,cheight);
  124. // context.restore();  No es necesario
  125. }
  126.  
  127. function drawPlayer(){
  128. // context.save();  No es necesario
  129. context.fillStyle="blue";
  130. context.fillRect(player.posX,player.posY, player.ancho,player.alto);
  131. // context.restore();  No es necesario
  132. }
  133.  
  134. function drawEnemigo(){
  135. //context.save();  No es necesario
  136. context.fillStyle="Red";
  137. context.fillRect(enemigo.posX,enemigo.posY, enemigo.ancho,enemigo.alto);
  138. //context.restore();  No es necesario
  139. }
  140.  
  141. setBackground();
  142. init();
  143. }
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
No se dibujar nada :(
Diseño Gráfico
LordKevin 3 2,313 Último mensaje 12 Abril 2006, 21:21 pm
por Azielito
Dibujar Linea
Programación Visual Basic
Xaina 9 2,651 Último mensaje 31 Octubre 2007, 03:39 am
por Xaina
Dibujar Arbol AVL
Java
JDtoar 3 11,642 Último mensaje 23 Abril 2008, 06:12 am
por JDtoar
Dibujar en java!!!!
Java
danielo- 7 9,885 Último mensaje 20 Noviembre 2009, 10:54 am
por danielo-
Ayuda borrar solo una extension jpg sin borrar nigun otro archivo
Programación Visual Basic
Otaku=) 4 3,100 Último mensaje 3 Julio 2012, 03:28 am
por Otaku=)
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines