问题:我在画布上画了一艘宇宙飞船。在它的x/y上空盘旋时,我在画布上画一个弧线,表示星舰武器的角和距离(考虑到当前的裸奔/面对)。目前,确定的角度正在绘制绿色,并延伸到武器射程值允许的范围内。
然而,我想用梯度填充确定的弧度来表示精度下降(即渐变开始于绿色,移动到橙色,转红越远离星舰的位置,角度)。
但是,我不知道如何用渐开线替换我的股票ctx.fill()。
var ship {
loc: {x, y}, // lets say 100, 100
facing: facing // lets say facing 0, i.e. straight right
weapons: objects (range, startArc, endArc) // lets say 50, 300, 60 -> 120 degree angle, so -60 and +60 from facing (0/360)
}
for (var i = 0; i < weapon.arc.length; i++){
var p1 = getPointInDirection(weapon.range, weapon.arc[i][0] + angle, pos.x, pos.y);
var p2 = getPointInDirection(weapon.range, weapon.arc[i][1] + angle, pos.x, pos.y)
var dist = getDistance( {x: pos.x, y: pos.y}, p1);
var rad1 = degreeToRadian(weapon.arc[i][0] + angle);
var rad2 = degreeToRadian(weapon.arc[i][1] + angle);
fxCtx.beginPath();
fxCtx.moveTo(pos.x, pos.y);
fxCtx.lineTo(p1.x, p1.y);
fxCtx.arc(pos.x, pos.y, dist, rad1, rad2, false);
fxCtx.closePath();
fxCtx.globalAlpha = 0.3;
fxCtx.fillStyle = "green";
fxCtx.fill();
fxCtx.globalAlpha = 1;
}是否有可能替换圆弧/globalalpha/fill,所以使用渐变流,而不是用颜色固定,如果是,怎么做?
谢谢
发布于 2016-09-01 08:32:02
用渐变填充弧线,动画只是为了好玩。
使用径向渐变,并将颜色设置为距离的一小部分。
函数createRadialGradient取6个数字--位置x,y和起始半径,以及梯度的位置x,y和末端半径。
颜色停止是通过渐变对象addColorStop函数添加的,该函数将0的值取到渐变的外部部分,颜色作为CSS颜色字符串。"#F00“或"rgba(200,0,0,0.5)”或“红色”
然后使用渐变作为填充样式。
var canvas = document.createElement("canvas");
document.body.appendChild(canvas);
var ctx = canvas.getContext("2d");
function update(time) {
ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// position of zones in fractions
var posRed = 0.8 + Math.sin(time / 100) * 0.091;
var posOrange = 0.5 + Math.sin(time / 200) * 0.2;
var posGreen = 0.1 + Math.sin(time / 300) * 0.1;
var pos = {
x: canvas.width / 2,
y: canvas.height / 2
};
var dist = 100;
var ang1 = 2 + Math.sin(time / 1000) * 0.5;
var ang2 = 4 + Math.sin(time / 1300) * 0.5;
var grad = ctx.createRadialGradient(pos.x, pos.y, 0, pos.x, pos.y, dist);
grad.addColorStop(0, "#0A0");
grad.addColorStop(posGreen, "#0A0");
grad.addColorStop(posOrange, "#F80");
grad.addColorStop(posRed, "#F00");
grad.addColorStop(1, "#000");
ctx.fillStyle = grad;
ctx.beginPath();
ctx.moveTo(pos.x, pos.y);
ctx.arc(pos.x, pos.y, dist, ang1, ang2);
ctx.fill();
requestAnimationFrame(update);
}
requestAnimationFrame(update);
https://stackoverflow.com/questions/39264504
复制相似问题