开源鸿蒙 OpenHarmony 3.1画布解析,教你如何完成飞机大战小游戏( 三 )


开源鸿蒙 OpenHarmony 3.1画布解析,教你如何完成飞机大战小游戏
文章图片

1. 首先列出游戏所用到的图片
private imgList:Array = ["xx.png","xx.png"…];
2. 将图片渲染到 canvas 画布上
let img:ImageBitmap = new ImageBitmap("图片路径(如common/images)/"+this.imgList[数组下标]);this.ctx.drawImage( img,150/* x坐标*/, 150/* y坐标*/, 600/*宽*/, 600/*高*/)
3. 绘制背景图片和战机向下移动的效果
this.ctx.drawImage(this.bg, 0, this.bgY);this.ctx.drawImage(this.bg, 0, this.bgY - 480);this.bgY++ == 480 && (this.bgY = 0);
4. 使用 Math.round 函数随机获取敌机图片并渲染到画布上 , 并且改变敌机 y 轴坐标 , 使它向下运动 。
Efight = Math.round(Math.random*7);//前七张为敌机图片 。 let img:ImageBitmap = new ImageBitmap("common/img"+this.imgList[Efight]);this.ctx.drawImage(img, 0, this.Eheight + 50);//渲染敌机
5. 在页面每隔 120s 出现一排子弹 , 之后减小或增大(x,y)轴的坐标达到子弹射出效果 。
let i= 0;setInterval(=>{ this.ctx.drawImage(this.bulImg1,image.x – 10 – (i *10) , image.x + (i *10)) this.ctx.drawImage(this.bulimg2, this. bulImg1,image.x – (i *10) , i image.x + (i *10)) this.ctx.drawImage(this.bulimg3, image.x + 10 + (i *10), image.x + (i *10))i ++;},120)
6. 使用 onTouch 方法获取战机移动位置 , 获取拖动的坐标后重新设置战机的图片坐标 , 使战机实现拖动效果 。
.onTouch((event)=>{ var offsetX = event.localX ||event.touches[0].localX; var offsetY = event.localY ||event.touches[0].localY; var w = this.heroImg[0].width, h = this.heroImg[0].height; var nx = offsetX - w / 2, ny = offsetY - h / 2; nx < 20 - w / 2 ? nx = 20 - w / 2 : nx > (this.windowWidth - w / 2 - 20) ? nx = (this.windowWidth - w / 2 - 20) : 0; ny < 0 ? ny = 0 : ny > (this.windowHeight - h / 2) ? ny = (this.windowHeight – h/2) : 0; this.hero.x = nx; this.hero.y = ny; this.hero.count = 2;
注:本示例引用了部分开源资源 , 感兴趣的开发者可参考此开源资源 , 结合文中的实现思路补全代码 。 (https://github.com/xs528 / game)
以上就是本期全部内容 , 期待广大开发者能通过 canvas 组件绘制出精美的图形 , 更多 canvas 组件的详细使用方法 , 请参考文档进行学习:

https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-canvas-canvas-0000000000621808

特别声明:本站内容均来自网友提供或互联网,仅供参考,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。