【Canvas与艺术】绘制古典火炮发射炮弹

【关键点】

古典火炮的简化与绘制(参看 https://www.cnblogs.com/heyang78/p/4161718.html)、火炮初速与仰角的关系。

【成图】

【代码】

<!DOCTYPE html>
<html lang="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<head>
     <title>使用HTML5/Canvas绘制古典火炮发射炮弹</title>
     <style type="text/css">
     .centerlize{
        margin:0 auto;
        width:1200px;
     }
     </style>
	 </head>

     <body onload="init();">
        <div class="centerlize">
            <canvas id="myCanvas" width="12px" height="12px" style="border:1px dotted black;">
                如果看到这段文字说您的浏览器尚不支持HTML5 Canvas,请更换浏览器再试.
            </canvas>
			<img id="myImg" src="161.jpg" style="display:none;"/>
        </div>
     </body>
</html>
<script type="text/javascript">
<!--
/*****************************************************************
* 将全体代码(从<!DOCTYPE到script>)拷贝下来,粘贴到文本编辑器中,
* 另存为.html文件,再用chrome浏览器打开,就能看到实现效果。
******************************************************************/

// canvas的绘图环境
var ctx;

// 高宽
const WIDTH=1200;
const HEIGHT=512;

// 舞台对象
var stage;

//-------------------------------
// 初始化
//-------------------------------
function init(){
	// 获得canvas对象
	var canvas=document.getElementById('myCanvas');  
	canvas.width=WIDTH;
	canvas.height=HEIGHT;

	// 初始化canvas的绘图环境
	ctx=canvas.getContext('2d');  
	ctx.translate(WIDTH/2,HEIGHT/2+200);// 原点平移

	// 准备
	stage=new Stage();	
	stage.init();

	// 开幕
    animate();

	// 响应键盘按下事件
    canvas.addEventListener('keydown', doKeyDown, true);
    window.addEventListener('keydown', doKeyDown, true);
	
	// 响应键盘弹起事件
	canvas.addEventListener('keyup', doKeyUp, true);
    window.addEventListener('keyup', doKeyUp, true);
	
	canvas.focus(); 
}

//------------------------------------
// 响应键盘按下事件
//------------------------------------
function doKeyDown(e) {
    var keyID = e.keyCode ? e.keyCode :e.which;
	
	// up arrow and W
    if(keyID === 38 || keyID === 87)  { 
		stage.toUp=true;
        e.preventDefault();
    }

	// down arrow and S
	if(keyID === 40 || keyID === 83)  { 
		stage.toDown=true;
        e.preventDefault();
    }

	// right arrow and D
	if(keyID === 39 || keyID === 68)  { 
		stage.toRight=true;
        e.preventDefault();
    }
    
	// left arrow and A
    if(keyID === 37 || keyID === 65)  { 
		stage.toLeft=true;
        e.preventDefault();
    }
    
	// SpaceBar
	if(keyID === 32 )  { 
		stage.canAddBall=true;
        e.preventDefault();
    }
}

//------------------------------------
// 响应键盘弹起事件
//------------------------------------
function doKeyUp(e) {
    var keyID = e.keyCode ? e.keyCode :e.which;
	
	// up arrow and W
    if(keyID === 38 || keyID === 87)  { 
		stage.toUp=false;
        e.preventDefault();
    }

	// down arrow and S
	if(keyID === 40 || keyID === 83)  { 
		stage.toDown=false;
        e.preventDefault();
    }

	// right arrow and D
	if(keyID === 39 || keyID === 68)  { 
		stage.toRight=false;
        e.preventDefault();
    }
    
	// left arrow and A
    if(keyID === 37 || keyID === 65)  { 
		stage.toLeft=false;
        e.preventDefault();
    }
	
	// SpaceBar
	if(keyID === 32 )  { 
		stage.canAddBall=false;
        e.preventDefault();
    }
}

// 播放动画
function animate(){    
    stage.update();	
	stage.paintBg(ctx);
	stage.paintFg(ctx);	 

	// 循环
    if(true){
		//sleep(100);
		window.requestAnimationFrame(animate);   
    }
}

// 舞台类
function Stage(){
	this.toUp=false;           // 仰角抬高
	this.toDown=false;         // 仰角降低
	this.elevation=-Math.PI/12;// 仰角
	this.balls=[];             // 放置炮弹的数组
	this.canAddBall=false;     // 可否加炮弹
	this.toRight=false;        // 炮口初速减少
	this.toLeft=false;         // 炮口初速增加
	this.velocity=6;           // 炮口初速

	// 初始化
	this.init=function(){
		// 测试用
		//var rebBall={"x":0,"y":-100,"vx":2.8,"vy":-8.1,"ay":0.1,"r":5,"color":"red"};
		//this.balls.push(rebBall);
	}

	// 更新
	this.update=function(){	
		// 按上箭头是仰角每次抬高0.1°
		if(this.toUp && this.elevation>-Math.PI/4){
			this.elevation+=-Math.PI/1800;
		}

		// 按上箭头是仰角每次降低0.1°
		if(this.toDown && this.elevation<Math.PI/4){
			this.elevation+=Math.PI/1800;
		}

		// 按左箭头是初速每次减少0.1
		if(this.toLeft && this.velocity>1){
			this.velocity+=-0.1;
		}
		// 按右箭头是初速每次增加0.1
		if(this.toRight && this.velocity<100){
			this.velocity+=0.1;
		}

		// 加炮弹
		if(this.canAddBall){
			// 原始炮弹数据
			var ball={"x":0,"y":-100,"vx":2.8,"vy":-8.1,"ay":0.2,"r":5,"color":"red","tracks":[]};

			// 调整到炮口
			let r=32;// 转轴到炮口的距离
			ball.x=-481.3+r*Math.cos(this.elevation);
			ball.y=-21.25+r*Math.sin(this.elevation);
			let velocity=this.velocity;// 初速
			ball.vx=velocity*Math.cos(this.elevation);
			ball.vy=velocity*Math.sin(this.elevation);

			// 加入数组
			this.balls.push(ball);

			// 一次加一颗
			this.canAddBall=false;
		}

		// 炮弹的运动及碰撞
		var delIdxArr=[];
		for(var i=0;i<this.balls.length;i++){
			var ball=this.balls[i];
			ball.tracks.push(createPt(ball.x,ball.y));// 记录轨迹

			// 触地反弹,速度衰减
			let groundLevel=30;
			if(ball.y+ball.r>=groundLevel){
				ball.y=groundLevel-ball.r;
				ball.vy*=-0.7;
			}

			// 越界球就准备删除了
			if(Math.abs(ball.x)>600){
				delIdxArr.push(i);
			}

			// 小球之间的碰撞检测(可选)
			/*for(var j=0;j<this.balls.length;j++){
				if(i!=j){
					var other=this.balls[j];
					
					var distance=Math.sqrt( Math.pow(ball.x-other.x,2)+Math.pow(ball.y-other.y,2));
					
					if(distance<=ball.r+other.r){
						// 两个小球碰撞后交换横向和纵向速度,不考虑发生旋转
						var vx=ball.vx;
						ball.vx=other.vx;
						other.vx=vx;
					
						var vy=ball.vy;
						ball.vy=other.vy;
						other.vy=vy;
					}
				}
			}*/

			// 球的运动,不考虑摩擦损耗
			ball.vy+=ball.ay;			
			ball.y+=ball.vy;

			ball.x+=ball.vx;
		}

		// 删除出界的球
		for(var idx in delIdxArr){
			this.balls.splice(idx,1);
		}
	}

	// 画背景
	this.paintBg=function(ctx){
		ctx.clearRect(-WIDTH/2,-HEIGHT/2-300,WIDTH,HEIGHT+100);// 清屏	

		// 背景白色
		ctx.fillStyle="white";
		ctx.fillRect(-WIDTH/2,-HEIGHT/2-300,WIDTH,HEIGHT+75);

		var img=document.getElementById("myImg");
		ctx.drawImage(img,0,0,800,533,-WIDTH/2,-HEIGHT/2-300,WIDTH,HEIGHT+75);

		// 画竖线
		for(var i=0;i<25;i++){
			var x1=-WIDTH/2+i*50;
			var y1=-HEIGHT/2-300;

			var x2=x1;
			var y2=y1+HEIGHT+75;

			ctx.beginPath();
			ctx.moveTo(x1,y1);
			ctx.lineTo(x2,y2);
			ctx.lineWidth=0.5;
			ctx.strokeStyle="navy";
			ctx.stroke();

			writeText(ctx,x2,y2+20,x2,"12px consolas","navy");
		}

		// 画横线
		for(var i=0;i<10;i++){
			var x1=-550;
			var y1=30-(i)*50;

			var x2=600;
			var y2=y1;

			ctx.beginPath();
			ctx.moveTo(x1,y1);
			ctx.lineTo(x2,y2);
			ctx.lineWidth=0.5;
			ctx.strokeStyle="navy";
			ctx.stroke();

			writeText(ctx,x1-20,y1,y1,"12px consolas","navy");
		}
		
		// 绘制大炮开始
		ctx.save();
		ctx.translate(-500,0);
		ctx.scale(0.25,0.25);

		// 绘制炮管开始-->
		ctx.save();
		ctx.translate(60,-80);
		ctx.rotate(this.elevation);		
		ctx.beginPath();
		ctx.moveTo(-160,35);
		ctx.lineTo(160,20);
		ctx.lineTo(160,-20);
		ctx.lineTo(-160,-35);
		ctx.arc(-160,0,35,Math.PI/2*3,Math.PI/2,true);
		ctx.closePath();		
		ctx.fillStyle="RGB(181,166,66)";
		ctx.fill();
		ctx.lineWidth=0.5;
		ctx.strokeStyle="black";
		ctx.stroke();

		// 炮轴
		ctx.beginPath();
		ctx.arc(0,0,26,0,Math.PI*2,true);
		ctx.closePath();
		ctx.lineWidth=0.2;
		ctx.strokeStyle="black";
		ctx.stroke();

		ctx.beginPath();
		ctx.arc(0,0,8,0,Math.PI*2,true);
		ctx.closePath();
		ctx.fillStyle="red";
		ctx.fill();

		ctx.restore();
		// 绘制炮管结束<--
		

		// 绘制炮架开始-->			
		// 撑杆
		ctx.save();
		ctx.translate(-50,30);
		ctx.rotate(-Math.PI/4);
		drawRoundRect(ctx,0,0,240,16,1)
		ctx.fillStyle="rgb(97,48,48)";
		ctx.fill();
		ctx.lineWidth=1;
		ctx.strokeStyle="black";
		ctx.stroke();
		ctx.restore();

		// 炮座
		ctx.save();
		ctx.translate(-10,-10);
		ctx.rotate(-Math.PI/4);
		drawRoundRect(ctx,0,0,240,30,1)
		ctx.fillStyle="rgb(97,48,48)";
		ctx.fill();
		ctx.lineWidth=1;
		ctx.strokeStyle="black";
		ctx.stroke();
		ctx.restore();		
		// 绘制炮架结束<--

		// 绘制轮子开始-->
		// 轮圈部分
		var r=100,R=120;
		for(var i=0;i<6;i++){
			var start=i*Math.PI*2/6;
			var end=start+Math.PI/3;

			var s1=createPt(r*Math.cos(start),r*Math.sin(start));
			var s2=createPt(R*Math.cos(start),R*Math.sin(start));
			var e1=createPt(r*Math.cos(end),r*Math.sin(end));
			var e2=createPt(R*Math.cos(end),R*Math.sin(end));

			ctx.beginPath();
			ctx.moveTo(s1.x,s1.y);
			ctx.lineTo(s2.x,s2.y);
			ctx.arc(0,0,R,start,end,false);
			ctx.lineTo(e1.x,e1.y);
			ctx.arc(0,0,r,end,start,true);
			ctx.closePath();
			ctx.fillStyle="rgb(97,48,48)";
			ctx.fill();
			ctx.lineWidth=1;
			ctx.strokeStyle="black";
			ctx.stroke();
		}

		// 轮辐部分
		var r=50;
		for(var i=0;i<12;i++){
			var theta=i*Math.PI*2/12+Math.PI/12;
			var x=r*Math.cos(theta);
			var y=r*Math.sin(theta);

			ctx.save();
			ctx.translate(x,y);
			ctx.rotate(theta);

			drawRoundRect(ctx,0,0,2*r,6,1)
			ctx.fillStyle="rgb(97,48,48)";
			ctx.fill();
			ctx.lineWidth=1;
			ctx.strokeStyle="black";
			ctx.stroke();
			ctx.restore();
		}

		// 轮轴部分
		ctx.beginPath();
		ctx.arc(0,0,20,0,Math.PI*2,false);
		ctx.closePath();
		ctx.fillStyle="rgb(97,48,48)";
		ctx.fill();		

		ctx.beginPath();
		ctx.arc(0,0,12,0,Math.PI*2,false);
		ctx.closePath();
		ctx.fillStyle="rgb(255,215,0)";
		ctx.fill();
		ctx.lineWidth=0.5;
		ctx.strokeStyle="black";
		ctx.stroke();

		// 绘制轮子结束<--

		// 支撑三角块
		ctx.save();
		ctx.translate(-150,120);
		var r=30;
		ctx.beginPath();
		ctx.moveTo(0,-r);
		ctx.lineTo(r,0);
		ctx.lineTo(-r,0);
		ctx.closePath();
		ctx.fillStyle="navy";
		ctx.fill();
		ctx.lineWidth=1;
		ctx.strokeStyle="black";
		ctx.stroke();
		ctx.restore();		

		// 炮轴基线,调图用,非表现元素
		/*var x=60,y=-80;
		ctx.beginPath();
		ctx.moveTo(0,120);
		ctx.lineTo(0,0);
		ctx.lineTo(x,y);

		ctx.lineWidth=1;
		ctx.strokeStyle="red";
		ctx.stroke();

		ctx.beginPath();
		ctx.arc(x,y,26,0,Math.PI*2,false)
		ctx.closePath();
		ctx.lineWidth=1;
		ctx.strokeStyle="red";
		ctx.stroke();*/

		ctx.restore();
		// 火炮绘制结束<--

		// 地面
		ctx.beginPath();
		ctx.moveTo(-WIDTH/2,30);
		ctx.lineTo(WIDTH/2,30);
		ctx.lineWidth=1;
		ctx.strokeStyle="black";
		ctx.stroke();

		for(var i=0;i<125;i++){
			var x1=-WIDTH/2+i*10;
			var y1=30;

			var x2=x1-10;
			var y2=y1+10;

			ctx.beginPath();
			ctx.moveTo(x1,y1);
			ctx.lineTo(x2,y2);
			ctx.lineWidth=0.5;
			ctx.strokeStyle="black";
			ctx.stroke();
		}

		var angle=(this.elevation/Math.PI*(-180)).toFixed(2)+"°";
		writeText(ctx,450,-420,"仰角:"+angle,"16px consolas","black");
		writeText(ctx,450,-400,"键盘上下键调节","16px consolas","black");

		var v=this.velocity.toFixed(2);
		writeText(ctx,450,-370,"炮口初速:"+v,"16px consolas","black");
		writeText(ctx,450,-350,"键盘左右键调节","16px consolas","black");

		writeText(ctx,450,-300,"按空格键发炮","16px consolas","black");
			
		writeText(ctx,550,20,"逆火原创","8px consolas","black");// 版权
	}

	// 画前景
	this.paintFg=function(ctx){
		for(var i=0;i<this.balls.length;i++){
			var ball=this.balls[i];
			drawColorBall(ctx,ball.x,ball.y,ball.r,ball.color);

			var arr=ball.tracks;
			ctx.beginPath();
			for(var j=0;j<arr.length;j++){
				ctx.lineTo(arr[j].x,arr[j].y);
			}
			ctx.lineWidth=0.4;
			ctx.strokeStyle="black";
			ctx.stroke();
		}
	}
}

/*----------------------------------------------------------
函数:用于绘制立体感彩色球
ctx:绘图上下文
x:球中心横坐标
y:球中心纵坐标
r:球半径
color:颜色
----------------------------------------------------------*/
function drawColorBall(ctx,x,y,r,color){
	ctx.beginPath();
	ctx.arc(x,y,r,0,Math.PI*2,false);
	ctx.closePath();
	var gnt=ctx.createRadialGradient(x+r/2,y-r/2,r/60,x,y,r);
	gnt.addColorStop(0,"white");
	gnt.addColorStop(0.9,color);
	gnt.addColorStop(1,"rgba(0,0,0,0)");
	ctx.fillStyle=gnt;
	ctx.fill();
}

/*----------------------------------------------------------
函数:用于绘制圆角矩形
ctx:绘图上下文
x:矩形中心横坐标
y:矩形中心纵坐标
width:矩形宽
height:矩形高
radius:圆角半径
----------------------------------------------------------*/
function drawRoundRect(ctx,x,y,width,height,radius){
	ctx.beginPath();
	ctx.moveTo(x-width/2+radius,y-height/2);
	ctx.lineTo(x+width/2-radius,y-height/2);
	ctx.arcTo(x+width/2,y-height/2,x+width/2,y-height/2+radius,radius);
	ctx.lineTo(x+width/2,y-height/2+radius);
	ctx.lineTo(x+width/2,y+height/2-radius);
	ctx.arcTo(x+width/2,y+height/2,x+width/2-radius,y+height/2,radius);
	ctx.lineTo(x+width/2-radius,y+height/2);
	ctx.lineTo(x-width/2+radius,y+height/2);
	ctx.arcTo(x-width/2,y+height/2,x-width/2,y+height/2-radius,radius);
	ctx.lineTo(x-width/2,y+height/2-radius);
	ctx.lineTo(x-width/2,y-height/2+radius);
	ctx.arcTo(x-width/2,y-height/2,x-width/2+radius,y-height/2,radius);
	ctx.closePath();
}

/*----------------------------------------------------------
函数:创建一个二维坐标点
x:横坐标
y:纵坐标
Pt即Point
----------------------------------------------------------*/
function createPt(x,y){
	var retval={};
	retval.x=x;
	retval.y=y;
	return retval;
}

/*----------------------------------------------------------
函数:延时若干毫秒
milliseconds:毫秒数
----------------------------------------------------------*/
function sleep(milliSeconds) {
	const date = Date.now();
	let currDate = null;
	while (currDate - date < milliSeconds) {
		currDate = Date.now();
	} 
}

/*----------------------------------------------------------
函数:书写文字
ctx:绘图上下文
x:横坐标
y:纵坐标
text:文字
font:字体
color:颜色
----------------------------------------------------------*/
function writeText(ctx,x,y,text,font,color){
	ctx.save();
	ctx.textBaseline="bottom";
	ctx.textAlign="center";
	ctx.font = font;
	ctx.fillStyle=color;
	ctx.fillText(text,x,y);
	ctx.restore();
}

/*-------------------------------------------------------------
人生的三个阶段:
接收父母是普通人,
接受自己是普通人,
接受孩子是普通人。

人生的四个阶段:
一个天真对未来充满憧憬的童年,
一个敢于天公试比高的青年,
一个屡屡碰壁愤懑忧郁的中年
一个无力回天坦然接受一切的老年。
--------------------------------------------------------------*/
//-->
</script>

【底图】

以下是底图161.jpg

END

  • 36
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值