如何解决如何使用2D数组在画布上绘制形状
我正在制作一个游戏,需要从2d数组渲染到画布上
var map = [
[1,1,0],[0,1],0]
]
function drawmap(){
for(y = 0;y < map.length;y++){
for(x = 0;x < map[0].length;x++){
switch(map[y][x]){
case 0:
ctx.fillStyle = "black";
break;
case 1:
ctx.fillStyle = "white";
break;
}
ctx.fillRect(x,y,x + tilesize * 16,y + tilesize * 8)
}
}
}
但是结果很小并且扭曲,我认为他们的数学有问题,但是我可以弄清楚。 这是一张照片 The HTML file when its ran
解决方法
是的,你的数学不正确...
应为:ctx.fillRect(x * tilesize,y * tilesize,tilesize,tilesize)
假设您有正方形瓷砖
这里是一个示例
<canvas id="c" width=800 height=800></canvas>
<script>
const canvas = document.getElementById('c');
const ctx = canvas.getContext('2d');
var tilesize = 10
var map = [
[1,1,0],[0,2,3,1],0]
]
function drawmap() {
for (y = 0; y < map.length; y++) {
for (x = 0; x < map[0].length; x++) {
ctx.fillStyle = ["red","blue","cyan","yellow"][map[y][x]]
ctx.fillRect(x * tilesize,tilesize)
}
}
}
drawmap()
</script>
我也在使用颜色数组来设置填充样式:ctx.fillStyle = ["red","yellow"][map[y][x]]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。