JSFiddle - React, Tailwind, and code Playground
by genialus
HTML
<div id="wrapper">
<span>Click and drag (release to throw the ball)</span>
<canvas id="canvas" width="400" height="300"></canvas>
</div>
CSS
#canvas {
border:1px solid gray;
}
#wrapper {
height:600px;
width: 600px;
}
JavaScript
/*Math Utilities*/
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype = {
relative: function(to) {
return new Vector(to.x - this.x, to.y - this.y);
},
distance: function(to) {
return Math.sqrt(Math.pow(this.x - to.x, 2) + Math.pow(this.y - to.y, 2));
}
};
function Vector(x1, x2) {
this.x1 = x1;
this.x2 = x2;
}
Vector.prototype = {
add: function(other) {
return new Vector(this.x1 + other.x1, this.x2 + other.x2);
},
scale: function(by) {
return new Vector(this.x1 * by, this.x2 * by);
},
normalize: function() {
function norm(value) {
return value > 0 ? 1 : value < 0 ? -1 : 0;
}
return new Vector(norm(this.x1), norm(this.x2));
}
};
$(function() {
var canvasWidth = $("#wrapper").width(),
canvasHeight = $("#wrapper").height(),
r = 5,
canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
g = new Vector(0, .981),
drag = 0.70,
bound = {
x1: 0,
y1: 0
};
context.canvas.width = canvasWidth;
context.canvas.height = canvasHeight;
$(window).resize(function() {
bound.x2 = $("#wrapper").width() - r;
bound.y2 = $("#wrapper").height() - r;
}).trigger("resize");
function initLevel() {
context.clearRect(0, 0, canvasWidth, canvasHeight);
drawShape();
}
function Ball() {
this.position = new Point(0, 0);
this.velocity = new Vector(0, 0);
drag = 0.70;
}
Ball.prototype = {
collided: false,
remove: function() {
this.output.remove();
},
draw: function() {
//draw Ball
context.fillStyle = this.collided === true ? 'red' : '#bada55';
context.beginPath();
context.arc(this.position.x, this.position.y, r, 0, Math.PI * 2, true);
...