我在渲染径向渐变时遇到问题;实际上,只渲染渐变颜色列表的最后一种颜色。前三个圆圈是动画的。渐变和更新循环之间是否存在渲染动画的冲突? 谢谢 这是我的代码:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Disc and Animated-Circle</title>
<style>
#canvasOne {
position: absolute;
border: dotted 2px black;
left: 50%;
margin-left: -450px;
top: 50%;
margin-top: -250px;
}
</style>
<script type="text/javascript">
window.addEventListener("load", eventWindowLoaded, false);
function eventWindowLoaded() {
canvasApp();
}
function canvasApp() {
var theCanvas = document.getElementById("canvasOne");
var context = theCanvas.getContext("2d");
drawScreen();
function drawScreen() {
//translation to centre canvas
context.setTransform(1, 0, 0, 1, 0, 0);
var x = canvasOne.width/2;
var y = canvasOne.height/2;
var circleWidth = 100;
var circleHeight = 100;
context.translate(x+.5*circleWidth, y+.5*circleHeight);
context.save();
//speed
r += speed;
//canvas
context.fillStyle = "blue";
context.fillRect(-(canvasOne.width/2+circleWidth/2), -(canvasOne.height/2+circleHeight/2), canvasOne.width, canvasOne.height);
//circle 1
context.strokeStyle = "#66f";
context.lineWidth = 4;
context.beginPath();
context.arc(-circleWidth/2, -circleHeight/2, r,(Math.PI/180)*0,(Math.PI/180)*360, false);
context.closePath();
//call circle 1
context.stroke();
context.restore();
//circle 2
context.strokeStyle = "#69f";
context.lineWidth = 4;
context.beginPath();
context.arc(-circleWidth/2, -circleHeight/2, r+4,(Math.PI/180)*0,(Math.PI/180)*360, false);
context.closePath();
//call circle 2
context.stroke();
context.restore();
//circle 3
context.strokeStyle = "#6cf";
context.lineWidth = 4;
context.beginPath();
context.arc(-circleWidth/2, -circleHeight/2, r+8,(Math.PI/180)*0,(Math.PI/180)*360, false);
context.closePath();
//call circle 3
context.stroke();
context.restore();
//disc gradient
var grad = context.createRadialGradient(100, 100, 0, 100, 100, 100);
grad.addColorStop(0, 'white');
grad.addColorStop(.5, 'grey');
grad.addColorStop(1, 'black');
context.fillStyle = grad;
//disc
context.beginPath();
context.arc(-circleWidth/2, -circleHeight/2, 100, (Math.PI/180)*0,(Math.PI/180)*360, false);
context.closePath();
//call disc
context.fill();
} //end drawScreen
var speed = 20;
var r = 100;
setInterval(drawScreen, 200);
} //end canvasApp
</script>
</head>
<body>
<canvas id="canvasOne" width="900" height="500">
Canvas is not supported.
</canvas>
</body>
</html>
答案 0 :(得分:0)
渐变的中心位于(100,100),这不是圆的中心。
更改行
var grad = context.createRadialGradient(100, 100, 0, 100, 100, 100);
到
var grad = context.createRadialGradient(-circleWidth/2, -circleHeight/2, 0, -circleWidth/2, -circleHeight/2, 100);