当前位置:编程学习 > html/css >>

HTML5游戏开发---弹跳球

本游戏涉及的知识点有:

    1.绘制球、图像和渐变

     2.定时事件和碰撞检测


[html]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>第一个版本</title> 
    <style> 
    form { 
    width:330px; 
    margin:20px; 
    background-color:brown; 
    padding:20px; 
    } 
    </style> 
    <script type="text/javascript"> 
        // 盒子左上角位置 
        var boxX = 20;       
        var boxY = 30; 
         
        // 盒子大小 
        var boxWidth = 350; 
        var boxHeight = 250; 
         
        // 小球大小 
        var ballRadius = 10; 
         
        // 碰撞检测位置 
        var boxBoundLeft = boxX + ballRadius;                   // 左边界 
        var boxBoundRight = boxX + boxWidth - ballRadius;       // 右边界 
        var boxBoundTop = boxY + ballRadius;                    // 上边界 
        var boxBoundBottom = boxY + boxHeight - ballRadius;     // 下边界 
         
        // 小球位置 
        var ballX = 50; 
        var ballY = 50; 
         
        // 小球位移 
        var ballDx = 4; 
        var ballDy = 8; 
         
        var ctx ; 
         
        // 用于填充球的图片 
        var img = new Image(); 
        img.src = "pearl.jpg"; 
         
        // 用于绘制墙的渐变 
        var grad ; 
         
        // 用于渐变的填充颜色 
        var hue = [ 
            [255,0,0], 
            [255,255,0], 
            [0,255,0], 
            [0,255,255], 
            [0,0,255], 
            [255,0,255] 
        ]; 
        function init() 
        { 
            ctx = document.getElementById("canvas").getContext("2d"); 
            ctx.lineWidth = ballRadius; 
             
            grad = ctx.createLinearGradient(boxX,boxY,boxX+boxWidth,boxY+boxHeight); 
             
            // 遍历取出没一个颜色的RGB值 
            for(var h = 0; h <hue.length; h++) 
            { 
                var color = "rgb("+hue[h][0]+","+hue[h][1]+","+hue[h][2]+")"; 
                grad.addColorStop(h/6,color); 
            } 
             
            ctx.fillStyle = grad; 
            moveball(); 
            setInterval(moveball,30);    
        } 
         
        function moveball() 
        { 
            // 清空画布 
            ctx.clearRect(boxX,boxY,boxWidth,boxHeight); 
            // 绘制墙体 
            // 绘制左墙 
            ctx.fillRect(boxX,boxY,ballRadius,boxHeight); 
            // 绘制右墙 
            ctx.fillRect(boxBoundRight,boxY,ballRadius,boxHeight); 
            // 绘制上墙 
            ctx.fillRect(boxX,boxY,boxWidth,ballRadius); 
            // 绘制下墙 
            ctx.fillRect(boxX,boxBoundBottom,boxWidth,ballRadius); 
            //ctx.strokeRect(boxX,boxY,boxWidth,boxHeight); 
      

补充:web前端 , HTML 5 ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,