html5 canvas-2.用canvas制作一个猜字母的小游戏

2019-01-28 19:35:57王冬梅

下面我们看看drawScreen都干了什么。

复制代码

function drawScreen() {
//background
context.fillStyle = '#ffffaa';
context.fillRect(0, 0, 500, 300);
//box
context.strokeStyle = '#000000';
context.strokeRect(5, 5, 490, 290);
context.textBaseLine = 'top';
//date
context.fillStyle = '#000000';
context.font = '10px_sans';
context.fillText(today, 150, 20);
//message
context.fillStyle = '#ff0000';
context.font = '14px_sans';
context.fillText(message, 125, 40);
//guesses
context.fillStyle = '#109910';
context.font = '16px_sans';
context.fillText('Guesses:' + guesses, 215, 60);
//higher or lower
context.fillStyle = '#000000';
context.font = '16px_sans';
context.fillText('Higher or Lower:' + higherOrLower, 150, 125);
//letters guessed
context.fillStyle = '#ff0000';
context.font = '16px_sans';
context.fillText('Letters Guessed:' + lettersGuessed.toString(), 10, 260);
if (gameOver) {
context.fillStyle = "#FF0000";
context.font = "40px _sans";
context.fillText("You Got It!", 150, 180);
}
}

代码很简单,就是绘制背景,还有文字信息。下面我们介绍导入图像的功能,当我们点击“Export Canvas Image”按钮的时候,会打开一个新的页面,显示当前的图像。注意toDataURL()方法,他会返回一个64位的png图片数据。

复制代码

$('#createImageData').click(function () {
window.open(theCanvas.toDataURL(), 'canvasImage', 'left=0,top=0,width=' + theCanvas.width + ',height=' + theCanvas.height + ',toolbar=0,resizab le=0');
});

大家还是直接运行demo,查看最终效果吧。demo下载地址:html5canvas.guessTheLetter.zip