画布绘图问题-使用forEach



我想画一条由像素组成的蛇,但forEach方法不能很好地工作。我该怎么办?

var canvas = document.getElementById("canvas")
var ctx = canvas.getContext("2d")
let snake = [ {x:160, y:200},
{x:170, y:200},
{x:180, y:200},
{x:190, y:200},
{x:200, y:200}
]
function drawSnakePixels(pixels){
ctx.fillStyle = "green"
ctx.strokeStyle = "black"
ctx.fillRect(pixels.x, pixels.y, 10, 10)
ctx.strokeRect(pixels.x,pixels.y)
}
function drawSnake(){
snake.forEach(drawSnakePixels)
}
drawSnake()
<canvas id="canvas"></canvas>

Vh将使其具有响应性,而使图像d-inline-block将使其达到您给定的大小。

EDIT:VH=视口高度,与引导程序的框架相结合有点复杂;除非您对bootstrap的系统有广泛的了解。

代码笔

<div class="card border-dark">
<img class="d-inline-block w-50" src="https://lh6.googleusercontent.com/-eB7I9skBrSc/AAAAAAAAAAI/AAAAAAAAAYI/q5R5BsF_kWg/photo.jpg?sz=1000" style="margin:auto;" alt="yusuf's picture">
<div class="card-body">
<h2 class="card-header text-dark border-light bg-transparent">header</h2>
<h5 class="card-title text-dark">title</h5>
<p class="card-text text-dark">Lorem ipsum dolor sit amet, consectetur 
adipisicing elit,sed do eiusmod tempor incididunt ut labore et dolore magna 
aliqua.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore 
</p>
<button type="button" class="btn bg-light text-white bg-dark dark mb-2"  >push</button>
<div class="card-footer bg-transparent  text-dark border-light">
Created 2020-08-12
</div>
</div>
</div>

您可以尝试:

function drawSnake(){
snake.forEach(pixel=>{
drawSnakePixels(pixel)
}

forEach((循环";名称";数组中的每个元素,此处为"pixel"。然后函数drawSnakePixels运行;命名为";元素"pixel"。

第一个问题是您没有正确使用ctx.strokeRect,它有四个参数,而您只提供了两个参数。您提供了X和Y位置,但没有提供宽度和高度。

https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/strokeRect

很明显,从代码的其余部分来看,你的意思是它们的大小是10像素,所以我把这些值放进去,你是对的,你在画布上看不到任何东西。为了得到一个完整的答案,下面是经过更正的JS代码。

ctx.strokeRect(pixels.x,pixels.y, 10, 10)

原因是什么?您尚未在画布元素上定义高度或宽度。画布的默认大小为150高、300宽(https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/height和https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/width)

你试图画得太低,所以看不见。你的坐标从Y=200开始,在视线之外整整50个像素。

对HTML进行简单的调整就可以解决这个问题:

<canvas id="canvas" width="300" height="300"></canvas>

最新更新