Last active
August 29, 2015 14:09
-
-
Save hanigamal/1335186bd90c4e55ad30 to your computer and use it in GitHub Desktop.
Drawing Examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Draw Rectangles | |
@include <canvas> | |
@use fillRect() or fill() or stroke() to render to canvas | |
*/ | |
function drawRects() { | |
var ctx = document.getElementById('canvas').getContext('2d'); | |
ctx.fillStyle = "rgb(200,0,0)"; | |
ctx.fillRect(10, 10, 55, 50); | |
ctx.fillStyle = "rgba(0, 0, 200, 0.5)"; | |
ctx.fillRect(30, 30, 55, 50); | |
} | |
/* | |
Draw Path | |
@include <canvas> | |
@use fill() or stroke() to render the path to the canvas | |
*/ | |
function drawPath() { | |
var ctx = document.getElementById('canvas').getContext('2d'); | |
ctx.fillStyle = "red"; | |
ctx.beginPath(); | |
ctx.moveTo(30, 30); | |
ctx.lineTo(150, 150); | |
// was: ctx.quadraticCurveTo(60, 70, 70, 150); which is wrong. | |
ctx.bezierCurveTo(60, 70, 60, 70, 70, 150); // <- this is right formula for the image on the right -> | |
ctx.lineTo(30, 30); | |
ctx.fill(); | |
} | |
/* | |
No <canvas> required | |
@include jQuery 1.3 at minimum | |
*/ | |
$(document).ready( | |
function() { | |
line(50,30, 100, 150); | |
circle(110,110, 100); | |
} | |
); | |
// Draw a line | |
function line(x1, y1, x2, y2) { | |
c = $(document.body); | |
var dx = Math.abs(x2-x1); | |
var dy = Math.abs(y2-y1); | |
var d = Math.max(dx, dy); | |
var i=0; for(i=0; i < d; i++) { | |
var img = $(document.createElement('img')).attr('src', 'blank.gif'); | |
var div = $(document.createElement('div')).width(1).height(1).css({'background-color': '#f00', position: 'absolute', left: Math.min(x1,x2)+(i*dx/d), top: Math.min(y1,y2)+(i*dy/d) }); | |
div.append(img); | |
c.append(div); | |
} | |
} | |
// Draw a circle | |
function circle(x, y, r) { | |
c = $(document.body); | |
var l = 2 * Math.PI * r; | |
var i=0; for(i=0; i < l * (1+((10-Math.log(r+1))/10)); i++) { | |
var x2 = r * Math.sin(360 * i/l); var y2 = r * Math.cos(360 * i/l); | |
var img = $(document.createElement('img')).attr('src', 'blank.gif'); | |
var div = $(document.createElement('div')).width(1).height(1).css({'background-color': '#f00', position: 'absolute', left: x+x2, top: y+y2 }); | |
div.append(img); | |
c.append(div); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment