Skip to content

Instantly share code, notes, and snippets.

@webapprentice
Last active August 29, 2015 14:02
Show Gist options
  • Save webapprentice/12f9f73d85725bc1c8e4 to your computer and use it in GitHub Desktop.
Save webapprentice/12f9f73d85725bc1c8e4 to your computer and use it in GitHub Desktop.
2D Graphics - Introduction to Canvas
<canvas id='mycanvas' width='500' height='300' style='border: 1px solid black'></canvas>
</div>
<script>
var canvas = document.getElementById("mycanvas");
var context = canvas.getContext("2d");
// Draw horizontal line
context.strokeStyle = '#f00';
context.beginPath();
context.moveTo(20, 25);
context.lineTo(100, 25);
context.closePath();
context.stroke();
context.beginPath();
context.moveTo(20, 50.5);
context.lineTo(100, 50.5);
context.closePath();
context.stroke();
// Draw triangle and fill it
context.strokeStyle = '#00f';
context.fillStyle = '#0ff';
context.beginPath();
context.moveTo(20, 100);
context.lineTo(100, 100);
context.lineTo(60, 160);
context.lineTo(20, 100);
// context.closePath();
context.stroke();
context.fill();
// Draw a rectangle
context.strokeStyle = '#000';
context.fillStyle = '#ff0';
context.strokeRect(30, 180, 60, 100);
context.fillRect(30, 180, 60, 100);
// Draw an arc
context.strokeStyle = '#000';
context.fillStyle = '#f0f';
context.beginPath();
context.arc(200, 50, 50, 0, Math.PI, false);
context.stroke();
// Draw a circle
context.strokeStyle = '#000';
context.fillStyle = '#ddd';
context.beginPath();
context.arc(200, 200, 50, 0, 2*Math.PI, false);
context.fill();
context.stroke();
// Draw some text
context.fillStyle = '#f00';
context.font = "24px sans-serif";
context.fillText("Hello Canvas", 300, 50);
// Include an Image
// 'onload' is necessary to ensure image is available before trying to use it
var logo = new Image();
logo.src = "craic_logo_64.png";
logo.onload = function() {
context.drawImage(logo, 340, 80);
};
// Draw Curves
context.strokeStyle = '#000';
context.beginPath();
context.moveTo(300, 200);
context.quadraticCurveTo(400,150,350,250);
context.stroke();
context.strokeStyle = '#000';
context.beginPath();
context.moveTo(400, 200);
context.bezierCurveTo(500,150,500,150,450,250);
context.stroke();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment