I’m trying to create a canvas script that visually draws a cubic bezier-curve, but so far I’ve been unsuccessful making my lines connect. See the code here
var canvas=document.getElementById("canvas");
var c = canvas.getContext("2d");
// Bezier eq. code
coord = function(x,y) { if(!x) var x=0; if(!y) var y=0; return {x: x, y: y}; }
B1 = function(t) { return (t*t*t); }
B2 = function(t) { return (3*t*t*(1-t)); }
B3 = function(t) { return (3*t*(1-t)*(1-t)); }
B4 = function(t) { return ((1-t)*(1-t)*(1-t)); }
function getBezier(t,C1,C2,C3,C4) {
var pos = new coord();
pos.x = C1.x * B1(t) + C2.x * B2(t) +C3.x * B3(t) + C4.x * B4(t);
pos.y = C1.y * B1(t) + C2.y * B2(t) + C3.y * B3(t) + C4.y * B4(t);
return pos;
}
//Ctrl points.
P1 = coord(12,12);
P2 = coord(90,1);
P3 = coord(0,190);
P4 = coord(150,150);
t=0;
function drawbez() {
if (t == 0) {var interval = setInterval('drawbez()',1);}
var curpos = getBezier(t2,P1,P2,P3,P4); // Staðan í ferlinum
if (t > 1) { clearInterval(interval); return; }
c2.moveTo(curpos.x,curpos.y);
c2.lineTo(curpos.x+t2,curpos.y+t2);
c2.stroke();
t = t+0.01
}
Any ideas?
I did a code using random numbers using exactly the same drawing commands and that actually gave me connected lines.
See code on HTML here
Using Bezier-curves tutorial from 13th Parallel
http://13thparallel.com/archive/bezier-curves/
Hey, I got it to work by changing your code to the following:
Please see this fiddle for a working example.
Basically,
t2was never declared,intervalwas out of scope, thesetTimeout()reference todrawbezseemed to be out of scope (possibly because you specified a string function name rather than a direct object reference), and removing the.moveTo()as mentioned in John Green’s answer gave a much smoother line.