Skip to content

Instantly share code, notes, and snippets.

@cngeru
Last active April 27, 2019 12:46
Show Gist options
  • Save cngeru/fabe3e08d85b931f5d9d68659dabf38e to your computer and use it in GitHub Desktop.
Save cngeru/fabe3e08d85b931f5d9d68659dabf38e to your computer and use it in GitHub Desktop.
<canvas id="surface" width="600" height="400"></canvas>
import 'dart:html';
import 'dart:math' show pi;
CanvasElement canvas;
CanvasRenderingContext2D ctx;
const double RADIUS = 15.0;
class Ball {
double radius;
double startX = 50;
double startY = 50;
double velocityX = 0;
double velocityY = 0;
Ball(this.radius);
}
void main() {
canvas = querySelector('#surface');
ctx = canvas.getContext('2d');
var ball = new Ball(RADIUS);
void doMouseDown(event) {
ball.startX = event.page.x;
ball.startY = event.page.y;
}
canvas.onMouseDown.listen(doMouseDown);
void draw(num time) {
ctx.save();
ctx.fillStyle = "rgba(200, 0, 200, .3)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.restore();
ball.startX += ball.velocityX;
ball.startY += ball.velocityY;
ball.velocityX *= .99;
ball.velocityY *= .99;
ball.velocityY += .25;
ball.velocityX += .25;
if (ball.startY + ball.radius > canvas.height) {
ball.startY = canvas.height - ball.radius;
ball.velocityY = -(ball.velocityY).abs();
}
;
if (ball.startX + ball.radius > canvas.width) {
ball.startX = canvas.width - ball.radius;
ball.velocityX = -(ball.velocityX).abs();
}
;
ctx.save();
ctx.translate(ball.startX, ball.startY);
ctx.fillStyle = "#ffff00";
ctx.beginPath();
ctx.arc(0, 0, ball.radius, 0, pi * 2, true);
ctx.closePath();
ctx.fill();
ctx.restore();
window.requestAnimationFrame(draw);
};
window.requestAnimationFrame(draw);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment