Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body onload="init();">
  <canvas id="moncanvas" width="400" height="400"></canvas>
</body>
</html>
 
canvas {
  border: 1px solid black;
  //background-color:lightblue;
}
 
// Variable qui correspond au canvas
var monCanvas;
// contexte graphique 2D
var ctx;
var monstre = {x:150, y:150, v:1, angle:0}
function init() { 
  console.log("page chargée");
  // On initialise la variable qui pointe sur le canvas
  monCanvas = document.getElementById("moncanvas");
  
  // Initialisation du contexte
  ctx = monCanvas.getContext('2d');
  
  // enfin on démarre le vrai dessin en
  // appelant la méthode draw
  draw();
  
} 
function draw() {
  // Pour dessiner dans un canvas, on doit
  // utiliser un objet qui s'appelle le 
  // contexte graphique. Il en existe un pour
  // le dessin en 2D et un pour le dessin
  // en 3D. C'est à partir du contexte qu'on
  // peut appeler les fonctions pour dessiner
  
  // Mode immediat
  
  //drawMonstre(150, 150);
  animeMonstre();
  
}
function drawMonstre(x, y, angle) {
  ctx.save();
  ctx.translate(x, y);
  ctx.rotate(angle);
  ctx.translate(-150, -150);
  
  //ctx.scale(0.5, 0.5);
  
  ctx.strokeRect(55, 10, 300, 300);
  drawYeux();
  drawBouche();
  ctx.restore();
}
function drawBouche() {
  ctx.beginPath();
  ctx.moveTo(150, 200);
  ctx.lineTo(300, 200);
  
  ctx.stroke();
}
function drawYeux() {
  ctx.save();
  drawRectangle(100, 100, 'red');
  drawRectangle(250, 100, 'red');
  
  // POUR DESSINER UN CERCLE
 drawCercle(120, 120, 10, 'yellow');
  drawCercle(270, 120, 10, 'blue');
  ctx.restore();
}
function drawCercle(x, y, rayon, couleur) {
  ctx.save();
  ctx.fillStyle=couleur;
  
  // On démarre un nouveau chemin
  ctx.beginPath();
   ctx.arc(x, y, rayon, 0, Math.PI*2);
    ctx.fill(); // dessine tout ce qui est en attente depuis le dernier beginPath()
  ctx.restore();
}
function drawRectangle(x, y, color) {
  // Dans une fonction, toujours sauvegarder
  // le contexte au début
  ctx.save();
  ctx.lineWidth=10;
   ctx.fillStyle=color;
   ctx.fillRect(x, y, 50, 40);
  ctx.strokeStyle='rgb(255, 134, 0)';
  ctx.strokeRect(x, y, 50, 40);
  
    // le restaurer à la fin
  ctx.restore();  
}
function animeMonstre() {
  // 1 On efface le canvas
  ctx.clearRect(0, 0, monCanvas.width, monCanvas.height);
  
  // 2 On dessine les objets les objets
  drawMonstre(150+Math.random()*10, 200+Math.random()*10);
  
  // 3 on déplace le canvas
  
  // On rappelle la boucle d'animation pour passer à 
  // l'image suivante, si possible à 60 images/s
  requestAnimationFrame(animeMonstre);
}
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
anonymouspro
0viewers