以下是如何体现 Dave 使用数组来组织画布的好主意:
创建一个包含对所有 25 个画布的引用的数组(对 25 个上下文执行相同操作)
var canvases=[];
var contexts=[];
接下来,用所有画布和上下文填充数组:
for(var i=0;i<25;i++){
var canvas=document.getElementById("can"+(i<10?"0":""));
var context=canvas.getContext("2d");
canvases[i]=canvas;
contexts[i]=context;
}
如果您以前没有见过: i<10?"0":""
是一个内联 if/else 用于在您的较低编号的画布上添加前导零。
然后你可以像这样获取你的“can05”画布:
var canvas=canvases[4];
为什么是 4 而不是 5?数组是从零开始的,所以 canvases[0] 包含 can01。因此数组元素 4 包含您的第 5 个画布“can05”。
所以你可以像这样为你的“can05”获取绘图上下文:
var context=contexts[4];
正如 Dave 所说,“evals are evil”所以这里是如何获取“can05”的上下文并在其上绘制石头图像的方法。
var context=contexts[4];
context.drawImage(stoneImage,0,0);
这张石头图可以缩短为:
contexts[4].drawImage(stoneImage,0,0);
您甚至可以将这段缩短的代码放入一个函数中,以便于重用和修改:
function reImage( canvasIndex, newImage ){
contexts[ canvasIndex ].drawImage( newImage,0,0 );
}
然后,您可以通过调用该函数来更改任何画布上的图像:
reimage( 4,stoneImage );
而已!
evil-evals 已被击败(警告:永远不要再邀请他们到您的计算机上!)
这是示例代码和小提琴:http: //jsfiddle.net/m1erickson/ZuU2e/
此代码动态创建 25 个画布,而不是硬编码 25 个 html 画布元素。
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; padding:0px; margin:0px;border:0px; }
canvas{vertical-align: top; }
</style>
<script>
$(function(){
var canvases=[];
var contexts=[];
var grass=new Image();
grass.onload=function(){
// the grass is loaded
// now make 25 canvases and fill them with grass
// ALSO !!!
// keep track of them in an array
// so we can use them later!
make25CanvasesFilledWithGrass()
// just a test
// fill canvas#3 with gold
draw(3,"gold");
// fill canvas#14 with red
draw(14,"red");
}
//grass.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/grass.jpg";
//grass.src="grass.jpg";
function make25CanvasesFilledWithGrass(){
// get the div that we will fill with 25 canvases
var container=document.getElementById("canvasContainer");
for(var i=0;i<25;i++){
// create a new html canvas element
var canvas=document.createElement("canvas");
// assign the new canvas an id, width and height
canvas.id="can"+(i<10?"0":"")+i;
canvas.width=grass.width;
canvas.height=grass.height;
// get the context for this new canvas
var ctx=canvas.getContext("2d");
// draw the grass image in the new canvas
ctx.drawImage(grass,0,0);
// add this new canvas to the web page
container.appendChild(canvas);
// add this new canvas to the canvases array
canvases[i]=canvas;
// add the context for this new canvas to the contexts array
contexts[i]=ctx;
}
}
// test -- just fill the specified canvas with the specified color
function draw(canvasIndex,newColor){
var canvas=canvases[canvasIndex];
var ctx=contexts[canvasIndex];
ctx.beginPath();
ctx.fillStyle=newColor;
ctx.rect(0,0,canvas.width,canvas.height);
ctx.fill();
}
}); // end $(function(){});
</script>
</head>
<body>
<div id="canvasContainer"></div>
</body>
</html>