Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw an irregular/hand-drawn line using svg/canvas?

I want to draw a vertical line that is resizable (based on the page content), but that appears to be hand drawn, rather than straight.

I'm currently thinking of using SVG or Canvas to achieve this. The line will run down the side of my webpage, hence needs to be scalable between the top and bottom of the container. How can I achieve this?

like image 982
Jeepstone Avatar asked Jun 16 '11 13:06

Jeepstone


1 Answers

So you want to draw a line with jitter?

Try drawing a bunch of successive Bezier curves, with all of the Y-axis point parts equally spaced, and randomize the x values by some amount.

Here's an example to get you started:

var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');

function addJitteryBezier(fromx, fromy, tox, toy) {
 var diffx = tox - fromx;
 var diffy = toy - fromy;
 
 var neg = Math.random()*diffy/5; // so the x value can go positive or negative from the typical
    
    
 ctx.bezierCurveTo(
 -neg + fromx + 2*(Math.random()*diffy/8), fromy + .3*diffy,
 -neg + fromx + 2*(Math.random()*diffy/8), fromy + .6*diffy,
 tox, toy
 );   
}

ctx.beginPath();
ctx.moveTo(50,0);

var i = 0;
while (i < 500) {
    addJitteryBezier(50, i, 50, i+50);
    i+=  50;
}

ctx.stroke();
<canvas id="canvas1" width="500" height="500"></canvas>

http://jsfiddle.net/GfGVE/9/

like image 136
Simon Sarris Avatar answered Oct 14 '22 06:10

Simon Sarris