[tr][td]绘制图片主要有这三种方式,从下图能很清楚的知道各个参数的作用
[*]drawImage(image,dx,dy) [*]drawImage(image,sx,sy,sw,sh,dx,dy,dw,dh) [*]drawImage(image,dx,dy,dw,dh) 其中的 image 参数可以是 HTMLImageElement(img标签的元素)、HTMLCanvasElement (canvas标签的元素)和HTMLVideoElement(video的元素) 中的任一个对象。 下面以坦克大战的地图来示意怎么使用 ,其中资源图片为右图 先上基本结构,上节有讲过 [*] [*] [*] 你的浏览器不支持canvas! [*] [*] [*] 然后创建一个图片 [*]var mapImg =new Image();//创建一个图片 [*]mapImg.src = "http://www.w3cfuns.com/data/attachment/forum/201107/26/194717f9ijaam199j9jvkv.png"//坦克地图的图片地址,它的宽为64,高为16。 然后就可以画图了 [*]context.drawImage(mapImg); //在坐标0,0处画图,宽高为图片本身的宽高 [*]context.drawImage(mapImg, 100, 100); //在坐标100, 100处画图,宽高为图片本身的宽高 [*]context.drawImage(mapImg, 100, 200, 640, 233); //在坐标100, 200处画图,宽 640,高 233 [*]context.drawImage(mapImg, 16, 0, 16, 16, 200, 100, 64, 64);//在坐标200,100处画图,宽64,高64,图内容为 [*]距原图左边16,上边0的一个大小为16,16的截图 自己可以试验下[html] 你的浏览器不支持canvas! [/html] 然后可以试着构造坦克地图了,先定义一个画地图小方块的函数 [*]function drawTile(x, y, type)//参数分别为坐标x,y,和地图的类型 [*]function drawTile(x, y, type) [*] { [*] context.drawImage(mapImg, type * 16, 0, 16, 16, x, y, 16, 16); //type*16为距原图左边界距离 [*] } 再试着运行下 [html] 你的浏览器不支持canvas! [/html] 最后就是构造整个坦克地图了,定义地图如下,其中每个数字代表一种地图类型,0代表没有东西 [*]var map =var map = [*] [ [*] [0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0], [*] [0,0,3,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,3,0,0], [*] [3,3,3,3,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0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