Studyhtml5canvasOn the third day, I feel that it is still good It’s not fun and I forget about it in a blink of an eye, so I’m going to make a little game to play when I have free time! The game should pay attention to performance, and there are some logics that need to be considered. I think it also needs user modifiability, that is, user configuration. Let’s start our simple but interesting journey -
If you want to see the effect first, jump and try it out first! Step, of course you need a canvas
1 <canvas id="canvas" width="300" height="400">你的浏览器不支持Canvas</canvas>
The overall structure of JavaScript
is as follows:var定义一些变量 planeMoveTimer飞机移动监听/计时器 attackEnemyTimer发射炮弹计时器 onkeydown监听 onkeyup监听 drawPlane画飞机 drawEnemy画敌人First predefine some variables
var _keyA = _keyD = _keyW = _keyS = 0, // 存储按键状态 step = 8, // 飞机移动速率 w = 34, h = 44, // 飞机实际大小 planeX = 133, planeY = 356, // 飞机目前位置 planeSrc = "feiji.png", // 飞机素材位置 imgW = 177, imgH = 220, // 飞机源图尺寸 cw = 300, ch = 400, // 画布大小 canvas = document.getElementById("canvas"), ctx = canvas.getContext("2d");This game only uses An external resource is the
picture
. To obtain the address, please visit the project GitHub location link given at the bottom of this article. JumpLook at the two methods of drawing first
function drawPlane(x, y) { var img = new Image(); img.src = planeSrc; // 飞机源图地址 img.onload = function() { ctx.drawImage(img, 0, 0, imgW, imgH, planeX, planeY, w, h); } } function drawEnemy(){ for(var a=0;a<cw;a+=10) { for(var b=0;b<ch-300;b+=10) { ctx.beginPath(); ctx.fillStyle = "orange"; ctx.strokeStyle = "black"; ctx.strokeRect(a, b, 10 ,10); ctx.fillRect(a, b, 10, 10); ctx.closePath(); } } }##. # The picture of the airplane must be drawn in the onload() method. The current enemy is still a bunch of orange bricks that cannot move. Draw them at the top of the canvas by traversing
Then. , look at the two keyboard
events:
window.document.onkeydown = function(evt){ evt = (evt) ? evt : window.event; switch(evt.keyCode) { case 65: // A _keyA = 1; break; case 68: // D _keyD = 1; break; case 87: // W _keyW = 1; break; case 83: // S _keyS = 1; break; } } window.document.onkeyup = function(evt){ evt = (evt) ? evt : window.event; switch(evt.keyCode) { case 65: // A _keyA = 0; break; case 68: // D _keyD = 0; break; case 87: // W _keyW = 0; break; case 83: // S _keyS = 0; break; } }
As for why the variables _keyA, _keyD, _keyW, _keyS should be set in the two events instead of directly triggering the drawing event, the reason is—— When two keys are long pressed at the same time, the event cannot be triggered at the same time. The one who presses first will only trigger it once. Only the one who presses later can trigger the event all the time while the key is pressed. To put it simply, if I want to move to the upper left corner, at the same time Press A and W. Assume that A is a little slower than W, even if it is very small, then the movement path of the aircraft is to move up one step first and then move all the way to the left. This is obviously not what I want. I use 4 variables to store it. The status of the key. When the key is pressed, set its status to 1. When the key is pressed, set its status to 0. Then we use a timer to continuously read the status of these keys and update them in time The status of the aircraft.
The aircraft movement timer is as follows:var planeMoveTimer = window.setInterval(function(){ if(_keyA||_keyD||_keyW||_keyS){ ctx.clearRect(planeX, planeY, w, h); _keyA && (planeX-=step); _keyD && (planeX+=step); _keyW && (planeY-=step); _keyS && (planeY+=step); planeX>=0 || (planeX=0); planeX<=(cw-w) || (planeX=cw-w); planeY>=0 || (planeY=0); planeY<=(ch-h) || (planeY=ch-h); drawPlane(planeX, planeY); } }, 10);ctx.clearRect() is used to clear the original position of the aircraft in preparation for drawing the next state of the aircraft, but there is a very The big problem is that it directly clears the entire block. If the game has backgrounds and overlaps, doesn't it mean that these things that are not airplanes are also cleared? Forgive me for being ignorant, I will not consider this issue for now. By judging the button status, the step distance of each movement is the preset step, and the boundary processing is done Then the attack timer:
var attackEnemyTimer = window.setInterval(function(){ var cannonX = planeX+Math.floor(w/2); // 炮口X轴位置 var cannonY = planeY; // 炮口Y轴位置 var tmpTimer = window.setInterval(function(){ // 每颗炮弹的移动计时器 ctx.clearRect(cannonX-1, cannonY-3, 2, 3); cannonY -= 3; // 炮弹步距 if(cannonY<0){ // 炮弹的贯透效果 ctx.beginPath(); ctx.moveTo(cannonX, 100); // 100为enemy的最低位置 ctx.strokeStyle = "white"; ctx.lineWidth = "4"; // 模拟不规则毁坏,暂时尚未没实现 ctx.lineTo(cannonX, 0); ctx.stroke(); ctx.closePath(); window.clearInterval(tmpTimer); // 清除该炮弹的计时器 } ctx.clearRect(cannonX-1, cannonY-3, 2, 3); ctx.beginPath(); ctx.fillStyle="red"; ctx.fillRect(cannonX-1, cannonY-3, 2, 3); // 炮弹大小:2X3 ctx.closePath(); }, 0); }, 500);Launch one every 0.5s. For the cannonballs, each cannonball is set up with a separate timer for easy control. I also use the method of wiping first and then painting for the movement of the cannonballs. Since the movement of the cannonballs also has steps, the so-called penetration effect of the cannonballs is to directly draw a line with the same color as the background color. Just a straight line. Try modifying the cannonball stride to adjust the speed of the cannonball, as well as the size of the cannonball. This is the last step. There is nothing left to do. We need to draw the enemies and planes from the beginning!
1 drawPlane(); 2 drawEnemy();Done! I still want to continue to optimize and increase the playability, but I really don’t have time to do it. There are many other things to learn, so this game will be like this for now! Is not it simple! Haha, it’s embarrassing, the title is too tempting, I can’t help it!
The above is the detailed content of Share the sample code for creating html5 Star Trek yourself. For more information, please follow other related articles on the PHP Chinese website!

MicrodatainHTML5enhancesSEOanduserexperiencebyprovidingstructureddatatosearchengines.1)Useitemscope,itemtype,anditempropattributestomarkupcontentlikeproductsorevents.2)TestmicrodatawithtoolslikeGoogle'sStructuredDataTestingTool.3)ConsiderusingJSON-LD

HTML5introducesnewinputtypesthatenhanceuserexperience,simplifydevelopment,andimproveaccessibility.1)automaticallyvalidatesemailformat.2)optimizesformobilewithanumerickeypad.3)andsimplifydateandtimeinputs,reducingtheneedforcustomsolutions.

H5 is HTML5, the fifth version of HTML. HTML5 improves the expressiveness and interactivity of web pages, introduces new features such as semantic tags, multimedia support, offline storage and Canvas drawing, and promotes the development of Web technology.

Accessibility and compliance with network standards are essential to the website. 1) Accessibility ensures that all users have equal access to the website, 2) Network standards follow to improve accessibility and consistency of the website, 3) Accessibility requires the use of semantic HTML, keyboard navigation, color contrast and alternative text, 4) Following these principles is not only a moral and legal requirement, but also amplifying user base.

The H5 tag in HTML is a fifth-level title that is used to tag smaller titles or sub-titles. 1) The H5 tag helps refine content hierarchy and improve readability and SEO. 2) Combined with CSS, you can customize the style to enhance the visual effect. 3) Use H5 tags reasonably to avoid abuse and ensure the logical content structure.

The methods of building a website in HTML5 include: 1. Use semantic tags to define the web page structure, such as, , etc.; 2. Embed multimedia content, use and tags; 3. Apply advanced functions such as form verification and local storage. Through these steps, you can create a modern web page with clear structure and rich features.

A reasonable H5 code structure allows the page to stand out among a lot of content. 1) Use semantic labels such as, etc. to organize content to make the structure clear. 2) Control the rendering effect of pages on different devices through CSS layout such as Flexbox or Grid. 3) Implement responsive design to ensure that the page adapts to different screen sizes.

The main differences between HTML5 (H5) and older versions of HTML include: 1) H5 introduces semantic tags, 2) supports multimedia content, and 3) provides offline storage functions. H5 enhances the functionality and expressiveness of web pages through new tags and APIs, such as and tags, improving user experience and SEO effects, but need to pay attention to compatibility issues.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Linux new version
SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
