Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Drawing primitives on html canvas JS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Primitives app</title>
<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
function randint(min, max){
return Math.floor(min + Math.random() * (max-min));
}
function randomColor(){
var colors = ["#00ff00", "#00ffff", "#0099ff", "#6600ff", "#cc33ff", "#ff33cc", "#ff5050", "#ff9933",
"#ffff00", "#99ff33", "#66ccff", "#990033"];
return colors[randint(0, colors.length)];
}
function drawCircle(context, circle){
context.fillStyle = circle.color;
context.beginPath();
context.arc(circle.x, circle.y, circle.width/2, 0, 2 * Math.PI, false);
context.fill();
}
function drawRect(context, rect){
context.fillStyle = rect.color;
context.fillRect(rect.x, rect.y, rect.width, rect.height);
}
var Shapes = {
newShape: function(){
return {
x: randint(20, 380),
y: randint(20, 180),
width: randint(10, 50),
height: randint(10, 50),
color: randomColor(),
speed: +2,
draw: null
}
},
newRectangle: function(){
var rect = this.newShape();
rect.draw = drawRect;
return rect;
},
newCircle: function(){
var circle = this.newShape();
circle.height = circle.width;
circle.draw = drawCircle;
return circle;
}
};
var Drawer = {
shapes: [],
animating: false,
canvasCtx: null,
redraw: function(){
this.canvasCtx.clearRect(0, 0, 400, 200);
for(var i in this.shapes){
var shape = this.shapes[i];
shape.draw(this.canvasCtx, shape);
}
},
addRectangle: function(){
var rectangle = Shapes.newRectangle();
this.shapes.push(rectangle);
},
addCircle: function(){
var circle = Shapes.newCircle();
this.shapes.push(circle);
},
nextState: function(){
for(var i in this.shapes){
var shape = this.shapes[i];
shape.y += shape.speed;
if(shape.y <= 0 || shape.y >= 180){
shape.speed = -shape.speed
}
}
this.redraw();
}
};
function onAddClick(){
if($("#shapes_select").val() === 'Rectangle'){
Drawer.addRectangle()
} else if($("#shapes_select").val() === 'Circle'){
Drawer.addCircle()
}
Drawer.redraw();
}
function animate(){
Drawer.nextState();
if(Drawer.animating){
setTimeout(animate, 10);
}
}
function onAnimateClick(){
Drawer.animating = !Drawer.animating;
$("#animate_button").text(Drawer.animating?"Stop":"Animate");
animate();
}
$(document).ready(function(){
Drawer.canvasCtx = document.getElementById("myCanvas").getContext("2d");
$("#add_button").on("click", onAddClick);
$("#animate_button").on("click", onAnimateClick);
});
</script>
</head>
<body>
<canvas width="400" height="200" style="border: 1px solid grey;" id="myCanvas"></canvas>
<div style="width: 400px;">
<select id="shapes_select">
<option selected value="Rectangle">Rectangle</option>
<option value="Circle">Circle</option>
</select>
<button id="add_button">Add</button>
<button id="animate_button">Animate</button>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment