2016年5月4日 星期三

test三角形反彈

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
var ballRadius = 5;
var x = canvas.width/2;
var y = canvas.height-30;
var dx = 2;
var dy = -2;

function drawBall() {
   ctx.beginPath();
var height = 10*Math.sin(Math.PI/3);//计算等边三角形的高
ctx.moveTo(x,y); //从A(100,0)开始
ctx.lineTo(x-15,y+30);//从A(100,0)开始,画到B (0,173)结束
ctx.lineTo(x+15,y+30); //B(0,173)-C(200,173)
var grd = ctx.createLinearGradient(0,0,20,0);//使用渐变颜色填充,从(0,0)到(200,0) (左到右)
grd.addColorStop(0,"#4CE8B2"); //起始颜色
grd.addColorStop(1,"#EFD458"); //终点颜色
ctx.fillStyle=grd; //以上面定义的渐变填充
ctx.fill(); //闭合形状并且以填充方式绘制出来
}

function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    drawBall();
 
    if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) {
        dx = -dx;
    }
    if(y + dy > canvas.height-ballRadius || y + dy < ballRadius) {
        dy = -dy;
    }

 
    x += dx;
    y += dy;
}

setInterval(draw, 10);

沒有留言:

張貼留言