我的程序有问题。我想旋转三角形几次并在每次旋转时绘制它,但三角形改变了它的位置(我希望它在屏幕的中心)。 三角图是绘制函数。
<!DOCTYPE html>
<html>
<head>
<script>
var ctx, canvas;
window.requestAnimFrame = (function(callback) {
return (window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame) &&
function(callback) {
window.setTimeout(callback, 1000/1 );
};
})();
window.onload = function(){
canvas = document.getElementById('myCanvas');
ctx = canvas.getContext('2d');
//sciana
for(var i = 0; i < 6; i++){
drawLine(i);
}
}
function drawLine(a){
var bok = 400, xw = canvas.width/2, yw = 10, odstep = 10;
var tX = 10/Math.sqrt(3);
ctx.rotate(Math.PI /6); //here I rotate
ctx.save();
for(var i = xw; i >= xw - bok/2; i-=tX){
var r = Math.floor( 255 * Math.random());
var g = Math.floor( 255 * Math.random());
var b = Math.floor( 255 * Math.random());
ctx.translate(10/Math.sqrt(3), 10);
ctx.beginPath();
ctx.fillStyle = "rgb("+r+","+g+","+b+")";
ctx.arc(xw, 0, 6, 0, 2 * Math.PI, false);
ctx.fill();
ctx.closePath();
}
ctx.restore();
ctx.save();
for(var i = xw; i >= xw - bok/2; i-=10/Math.sqrt(3)){
var r = Math.floor( 255 * Math.random());
var g = Math.floor( 255 * Math.random());
var b = Math.floor( 255 * Math.random());
ctx.translate(-10/Math.sqrt(3), 10);
ctx.beginPath();
ctx.fillStyle = "rgb("+r+","+g+","+b+")";
ctx.arc(xw, 0, 6, 0, 2 * Math.PI, false);
ctx.fill();
ctx.closePath();
}
ctx.restore();
ctx.save();
xw = xw - bok/2 ;
yw = bok*Math.sqrt(3)/2;
for(var i = xw; i <= xw + bok; i+=10){
var r = Math.floor( 255 * Math.random());
var g = Math.floor( 255 * Math.random());
var b = Math.floor( 255 * Math.random());
ctx.translate(10,0);
ctx.beginPath();
ctx.fillStyle = "rgb("+r+","+g+","+b+")";
ctx.arc(xw, yw, 6, 0, 2 * Math.PI, false);
ctx.fill();
ctx.closePath();
}
ctx.restore();
requestAnimFrame(drawLine);
}
</script>
</head>
<body>
<canvas id="myCanvas" width="600" height="600" style="background-color:#D0D0D0">
Twoja przeglądarka nie obsługuje elementu Canvas.
</canvas>
</body>
</html>