如何使用canvas生成随机字母包裹的矩形?我使用j-query但不知道如何使用canvas。这是使用j-query生成随机字母的代码。
<script>
var letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
function randomNumber(max) {
var randomNum = Math.random();
var numExpanded = randomNum * max;
var numFloored = Math.floor(numExpanded);
return numFloored;
}
//create a function returning a random letter
function randomLetter() {
var random0to25 = randomNumber(letters.length);
var randomLetter = letters.charAt(random0to25);
return randomLetter;
}
//create a function creating a span containing a random letter and attaching it to body
function createLetter() {
var span = $("<span/>");
span.css("position", "absolute");
span.css("top", 0);
randomCol=randomNumber(760);
randomCol=randomCol+20;
//concatenation
span.css("left", randomCol+"px");
span.text(randomLetter());
span.appendTo("body");
return span;
}
//explain how to animate an element
function makeLetterFall() {
var letterElement = createLetter();
letterElement.animate({"top":"95%"}, 5000); //any ideas how not to use {} here?
}
//handle keyup, find a letter and remove it
/*function removeTypedLetter(pressedKey) {
var typedLetter = String.fromCharCode(pressedKey.keyCode);
var letterElement = $("span:contains("+typedLetter+")").first();
letterElement.remove();
}*/
//$(document).on("keyup", removeTypedLetter);
//make a new letter every second
setInterval(makeLetterFall, 1000);
</script
&GT;
答案 0 :(得分:0)
这是一个显示下降矩形字母的学习示例。
兴趣点:
context.measureText
.textAlign
&amp; .textBaseline
context.fillText('A',x,y)
context.strokeRect(x,y,width,height)
示例代码和演示:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
var x=150;
var y=10;
var fontsize=20;
var fontface='verdana';
ctx.font=fontsize+' '+fontface;
ctx.textAlign='center';
ctx.textBaseline='middle';
animate();
function drawLetter(letter,x,y){
var width=ctx.measureText(letter).width;
ctx.strokeRect(x,y,width,fontsize);
ctx.fillText(letter,x+width/2,y+fontsize/2,width,fontsize);
}
function animate(){
ctx.clearRect(0,0,cw,ch);
drawLetter('A',x,y);
x+=Math.random()*4-2;
y+=1;
if(y<ch){
requestAnimationFrame(animate);
}
}
&#13;
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
&#13;
<h4>Letter in Rect falling with random horizontal drifting</h4>
<canvas id="canvas" width=300 height=300></canvas>
&#13;