<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="canvas.js"></script>
</head>
<body onload="init();">
<canvas width = 500 height = 500 id="myCanvas"></canvas>
<button>Un bouton</button>
</body>
</html>
canvas {
background-color : lightpink;
border : 10px solid red;
}
var canvas;
var ctx;
var w, h;
var mousePos = {};
var tableauDesBalles = [];
var monstre = {
x:100,
y:100,
vitesseX : 0,
vitesseY: 0,
taille: 100,// vitesse en pixel/frame
draw : function(ctx) {
// sauve tous les états du contexte : couleur,
// épaisseur du trait, repère...
ctx.save();
// On déplace le repère
ctx.translate(this.x, this.y);
//ctx.scale(scale, scale);
// Là on peut dessiner !!!!!!
ctx.fillStyle = 'green';
ctx.fillRect(0, 0, this.taille, this.taille);
ctx.fillStyle = "black";
ctx.fillRect(20, 20, 10, 10);
ctx.fillRect(70, 20, 10, 10);
ctx.strokeStyle = "blue";
ctx.lineWidth = 5;
ctx.strokeRect(25, 60, 50, 10);
// On restaure le contexte
ctx.restore();
}
};
function init() {
//console.log("page chargee");
canvas = document.querySelector("#myCanvas");
w = canvas.width;
h = canvas.height;
ctx = canvas.getContext('2d');
// Creer des balles
creerPleinDeBalles(10);
creerLesEcouteurs();
requestAnimationFrame(animeLeMonstre);
}
function creerPleinDeBalles(nbBalles) {
for(var i=0; i < nbBalles; i++) {
var x = Math.random() * w;
var y = Math.random() * h;
var taille = 5 + Math.random()*30;
var v = 1+Math.random() * 4;
var angle = Math.random() * Math.PI * 2;
var r = Math.round(Math.random() * 255);
var g = Math.round(Math.random() * 255);
var b = Math.round(Math.random() * 255);
var couleur = "rgb(" + r + ',' + g + "," + b + ")";
tableauDesBalles[i] = new Balle(x, y, taille, v, angle, couleur);
}
}
function creerLesEcouteurs() {
// 1er param = le nom de l'évenement
// 2ème param la fonction écouteur, on appelle cela un callback,
// 3ème param (optionnel), si false = ne pas propager l'evenement
document.addEventListener('keydown', traiteToucheEnfoncee, false);
document.addEventListener('keyup', traiteToucheRelachee, false);
canvas.addEventListener('mousedown', traiteBoutonSourisEnfonce, false);
canvas.addEventListener('mouseup', traiteBoutonSourisRelache, false);
canvas.addEventListener('mousemove', traiteSourisDeplacee, false);
}
function traiteBoutonSourisEnfonce(evt) {
console.log("bouton souris enfonce no " + evt.button);
}
function traiteBoutonSourisRelache(evt) {
console.log("bouton souris relache no " + evt.button);
}
function traiteSourisDeplacee(evt) {
var rect = canvas.getBoundingClientRect();
//console.log("souris deplacee x= " + (evt.clientX - rect.left) + " y =" + (evt.clientY - rect.top));
mousePos.x = evt.clientX - rect.left;
mousePos.y = evt.clientY - rect.top;
monstre.x = mousePos.x;
monstre.y = mousePos.y;
}
function traiteToucheEnfoncee(evt) {
console.log("touche enfoncee code = " + evt.keyCode);
if(evt.keyCode === 39) {
// on va déplacer le monstre à droite
monstre.vitesseX = 1;
}
if(evt.keyCode === 37) {
// on va déplacer le monstre à gauche
monstre.vitesseX = -1;
}
if(evt.keyCode === 40) {
// on va déplacer le monstre vers le bas
monstre.vitesseY = 1;
}
if(evt.keyCode === 38) {
// on va déplacer le monstre vers le haut
monstre.vitesseY = -1;
}
}
function traiteToucheRelachee(evt) {
console.log("touche relachee code = " + evt.keyCode);
monstre.vitesseX = 0;
monstre.vitesseY = 0;
}
function traiteClick(evt) {
console.log("click");
}
function animeLeMonstre() {
// On efface le canvas
ctx.clearRect(0, 0, w, h);
// On dessine les balles
dessineEtDeplaceToutesLesBalles();
// On dessine le monstre
monstre.draw(ctx);
// on le déplace
monstre.x += monstre.vitesseX;
monstre.y += monstre.vitesseY;
// test collisions entre les balles et le mur
//testeCollisionsNBallesMurs();
// Si le monstre touche un mur il rebondit
if(monstre.x+100 > w) monstre.vitesseX = -monstre.vitesseX;
if(monstre.x < 0) monstre.vitesseX = -monstre.vitesseX;
// On rappelle la fonction d'animation à 60 im/s
requestAnimationFrame(animeLeMonstre);
}
// LES BALLES
function dessineEtDeplaceToutesLesBalles() {
for(var i=0; i < tableauDesBalles.length; i++) {
var balleCourante = tableauDesBalles[i];
balleCourante.move();
testCollisionAvecMurs(balleCourante);
balleCourante.draw(ctx);
}
}
function testCollisionAvecMurs(ball) {
// left
if (ball.x < ball.rayon) {
ball.x = ball.rayon;
ball.angle = -ball.angle + Math.PI;
}
// right
if (ball.x > w - (ball.rayon)) {
ball.x = w - (ball.rayon);
ball.angle = -ball.angle + Math.PI;
}
// up
if (ball.y < ball.rayon) {
ball.y = ball.rayon;
ball.angle = -ball.angle;
}
// down
if (ball.y > h - (ball.rayon)) {
ball.y = h - (ball.rayon);
ball.angle =-ball.angle;
}
}
// COLLISIONS CERCLE CERCLE
function circleCollide(x1, y1, r1, x2, y2, r2) {
var dx = x1 - x2;
var dy = y1 - y2;
return ((dx * dx + dy * dy) < (r1 + r2)*(r1+r2));
}
// COLLISIONS RECTANGE - RECTANGLE ET RECTANGLE-CERCLE
// Collisions between rectangle
function rectsOverlap(x0, y0, w0, h0, x2, y2, w2, h2) {
if ((x0 > (x2 + w2)) || ((x0 + w0) < x2))
return false;
if ((y0 > (y2 + h2)) || ((y0 + h0) < y2))
return false;
return true;
}
// Collisions between rectangle and circle
function circRectsOverlap(x0, y0, w0, h0, cx, cy, r) {
var testX=cx;
var testY=cy;
if (testX < x0) testX=x0;
if (testX > (x0+w0)) testX=(x0+w0);
if (testY < y0) testY=y0;
if (testY > (y0+h0)) testY=(y0+h0);
return (((cx-testX)*(cx-testX)+(cy-testY)*(cy-testY))<r*r);
}
// BALLES
function Balle(x, y, rayon, vitesse, angle, couleur) {
this.x = x;
this.y = y;
this.rayon = rayon;
this.vitesse = vitesse;
this.angle = angle;
this.couleur = couleur;
this.draw = function(ctx) {
ctx.save();
ctx.fillStyle = couleur;
//ctx.strokeRect(this.x, this.y, this.rayon, this.rayon);
ctx.beginPath();
ctx.arc(this.x, this.y, this.rayon, 0, 2*Math.PI);
ctx.fill();
ctx.restore();
};
this.move = function() {
var dx = this.vitesse * Math.cos(this.angle);
var dy = this.vitesse * Math.sin(this.angle);
this.x += dx;
this.y += dy;
};
}
Output
You can jump to the latest bin by adding /latest
to your URL
Keyboard Shortcuts
Shortcut | Action |
---|---|
ctrl + [num] | Toggle nth panel |
ctrl + 0 | Close focused panel |
ctrl + enter | Re-render output. If console visible: run JS in console |
Ctrl + l | Clear the console |
ctrl + / | Toggle comment on selected lines |
ctrl + ] | Indents selected lines |
ctrl + [ | Unindents selected lines |
tab | Code complete & Emmet expand |
ctrl + shift + L | Beautify code in active panel |
ctrl + s | Save & lock current Bin from further changes |
ctrl + shift + s | Open the share options |
ctrl + y | Archive Bin |
Complete list of JS Bin shortcuts |
JS Bin URLs
URL | Action |
---|---|
/ | Show the full rendered output. This content will update in real time as it's updated from the /edit url. |
/edit | Edit the current bin |
/watch | Follow a Code Casting session |
/embed | Create an embeddable version of the bin |
/latest | Load the very latest bin (/latest goes in place of the revision) |
/[username]/last | View the last edited bin for this user |
/[username]/last/edit | Edit the last edited bin for this user |
/[username]/last/watch | Follow the Code Casting session for the latest bin for this user |
/quiet | Remove analytics and edit button from rendered output |
.js | Load only the JavaScript for a bin |
.css | Load only the CSS for a bin |
Except for username prefixed urls, the url may start with http://jsbin.com/abc and the url fragments can be added to the url to view it differently. |