画布中的角度渐变 [英] Angle gradient in canvas

查看:26
本文介绍了画布中的角度渐变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找允许具有这种效果的代码在画布的笔触上.我已经有了一个动画圆形笔触,我只需要获得 ANGLE 渐变,不是线性的也不是径向的.我只有3个颜色.现有的可在此处获得(评论评级)

I'm looking for a code that permits to have this effect on a canvas' stroke. I've already got an animated circular stroke, I only need to get the ANGLE gradient, not linear and not radial. I've got only 3 colours. The existing one is available here (the review rating)

推荐答案

上下文 strokeStyle 可以是渐变:

A context strokeStyle can be a gradient:

// create a gradient

gradient = ctx.createLinearGradient(xStart, yStart, xEnd, yEnd);
gradient.addColorStop(0.0,"blue");
gradient.addColorStop(1.0,"purple");


// stroke using that gradient

ctx.strokeStyle = gradient;

使用渐变strokeStyle的示例代码和演示:http://jsfiddle.net/m1erickson/w46ps/

Example code and a Demo using a gradient strokeStyle: http://jsfiddle.net/m1erickson/w46ps/

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
    body{ background-color: ivory; }
    #canvas{border:1px solid red;}
</style>
<script>
$(function(){

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    function drawMultiRadiantCircle(xc, yc, r, radientColors) {
        var partLength = (2 * Math.PI) / radientColors.length;
        var start = 0;
        var gradient = null;
        var startColor = null,
            endColor = null;

        for (var i = 0; i < radientColors.length; i++) {
            startColor = radientColors[i];
            endColor = radientColors[(i + 1) % radientColors.length];

            // x start / end of the next arc to draw
            var xStart = xc + Math.cos(start) * r;
            var xEnd = xc + Math.cos(start + partLength) * r;
            // y start / end of the next arc to draw
            var yStart = yc + Math.sin(start) * r;
            var yEnd = yc + Math.sin(start + partLength) * r;

            ctx.beginPath();

            gradient = ctx.createLinearGradient(xStart, yStart, xEnd, yEnd);
            gradient.addColorStop(0, startColor);
            gradient.addColorStop(1.0, endColor);

            ctx.strokeStyle = gradient;
            ctx.arc(xc, yc, r, start, start + partLength);
            ctx.lineWidth = 30;
            ctx.stroke();
            ctx.closePath();

            start += partLength;
        }
    }

    var someColors = [];
    someColors.push('#0F0');
    someColors.push('#0FF');
    someColors.push('#F00');
    someColors.push('#FF0');
    someColors.push('#F0F');

    drawMultiRadiantCircle(150, 150, 120, someColors);

}); // end $(function(){});
</script>
</head>
<body>
    <canvas id="canvas" width=300 height=300></canvas>
</body>
</html>

这篇关于画布中的角度渐变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆