2

I need to add a gradient to a canvas. I have tested all solutions, but nothing works.

Original code:

ctx.strokeStyle = params.wheelBorderColor;
ctx.lineWidth = params.wheelBorderWidth;
ctx.font = params.wheelTextFont;
ctx.clearRect(0, 0, 500, 500);

var text = null,
    i = 0,
    totalJoiner = pplLength;
var width = ctx.measureText(text).width + blur * 2;

for (i = 0; i < totalJoiner; i++) {
    text = pplArray[i];
    var angle = startAngle + i * arc;
    ctx.fillStyle = colorCache.length > totalJoiner ? colorCache[i] : genHex(text);

    ctx.beginPath();
    // ** arc(centerX, centerY, radius, startingAngle, endingAngle, antiClockwise);
    ctx.arc(250, 250, params.outterRadius, angle, angle + arc, false);
    ctx.arc(250, 250, params.innerRadius, angle + arc, angle, true);
    ctx.stroke();
    ctx.fill();

    ctx.save();


    ctx.fillStyle = params.wheelTextColor;
    ctx.translate(250 + Math.cos(angle + arc / 2) * params.textRadius, 250 + Math.sin(angle + arc / 2) * params.textRadius);
    ctx.rotate(angle + arc / 2 + Math.PI / 1);

    ctx.fillText(text, -ctx.measureText(text).width / 2, 6);
    ctx.restore();
    ctx.closePath();
}

drawArrow();

And i add this code for gradiant and the fill() is already sent to original code

var grd = ctx.createLinearGradient(0.000, 150.000, 300.000, 150.000);

// Add colors
grd.addColorStop(0.000, 'rgba(0, 0, 0, 1.000)');
grd.addColorStop(1.000, 'rgba(255, 255, 255, 1.000)');

// Fill with gradient
ctx.fillStyle = grd;
ctx.fill();

The genHex() is:

color = "#666"; colorCache.push('#'+color); return '#'+color;"

Any guidance would be helpful.

3
  • 1
    what does't work? can you provide a Fiddle? May 20, 2014 at 10:48
  • The canvas is work but not gradiant i have edit post for view my original code and add code May 20, 2014 at 11:02
  • Please provide a fiddle on this site: jsfiddle.net
    – AdiT
    May 20, 2014 at 11:08

1 Answer 1

0

Are you drawing a rectangle within your context? Try something like this:

var canvas = document.getElementById('test-canvas');
var ctx = (canvas !== null ? canvas.getContext('2d') : null);
var grd = (ctx !== null ? ctx.createLinearGradient(0.000, 150.000, 300.000, 150.000) : null);

if (grd) {

    ctx.rect(0, 0, canvas.width, canvas.height);

    grd.addColorStop(0.000, 'rgba(0, 0, 0, 1.000)');
    grd.addColorStop(1.000, 'rgba(255, 255, 255, 1.000)');

    ctx.fillStyle = grd;

    ctx.fill();
}

I have posted a working example at JSFiddle: http://jsfiddle.net/briansexton/e6rC3/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.