Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use HTML5's Canvas API to make a simple word guessing game

Shulou Source: shulou.com Published: 2022-06-01 06:56:36 10月03日 Update

This article is a detailed introduction to "how to make a simple guessing game with HTML5 Canvas API". The content is detailed, the steps are clear, and the details are properly handled. I hope this article "how to make a simple guessing game with HTML5 Canvas API" can help you solve your doubts. Let's go deeper and learn new knowledge together with the ideas of Xiaobian.

< html lang = " en" >

< meta charset = " utf-8" />

< canvas id = " canvas_guess_the_letter"宽度= " 500"高度= " 300" >

你的浏览器不支持HTML5 Canvas

;

JS代码

JavaScript代码将内容复制到

/ **

* @作者拉斐尔

* /

window.addEventListener(" load" ,eventWindowLoaded, false );

var Debugger = function (){

};

Debugger.log = 函数(消息){

尝试 {

console.log(消息);

} 捕获(例外){

回报;

}

}

函数 eventWindowLoaded(){

canvasApp();

}

函数 canvasSupport(){

返回 Modernizr.canvas;

}

函数 canvasApp(){

VAR 猜测= 0;

var message = "猜字母从a(低)到z(高)的字母" ;

变数 字母= [ "" a" ," b" ," c" ," d" ," e" ," f" ," g" ," h" ," i" ," j" ," k" ," l " ,

" m" ," n" ," o" ," p" ," q" ," r" ," s" ," t" ," u" ," v" ," w" ," x" ," y" " ," z" ];

今天的var = 新的 Date();

var letterToGuess = "" ;

var HigherOrLower = "" ;

var letterGuessed = [];

var gameOver = false ;

如果(!canvasSupport()){

回报;

}

var theCanvas = document.getElementById(" canvas_guess_the_letter" );

var context = theCanvas.getContext(" 2d" );

initGame();

函数 initGame(){

var letterIndex = Math.floor(Math.random()* letters.length);

letterToGuess =字母[letterIndex];

猜测= 0;

letterGuessed = [];

gameOver = false ;

window.addEventListener(" keyup" ,eventKeyPressed, true );

var formElement = document.getElementById(" createImageData" );

formElement.addEventListener('click' ,createImageDataPressed, false );

drawScreen();

}

函数 eventKeyPressed(e){

如果(!gameOver){

var letterPressed = String.fromCharCode(e.keyCode);

letterPressed = letterPressed.toLowerCase();

猜测++;

letterGuessed.push(letterPressed);

如果(letterPressed == letterToGuess){

gameOver = true ;

} 其他 {

letterIndex = letters.indexOf(letterToGuess);

guessIndex = letters.indexOf(letterPressed);

如果(guessIndex

Tags: Guesses letters functions text content codes characters times messages users generation input production variables articles indexes or hints yes events Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Shulou Information Microsoft Shulou Technology Redmi