gpt4 book ai didi

javascript - html5 Canvas : clearRect() not working inside function

转载 作者:行者123 更新时间:2023-11-28 15:02:36 25 4
gpt4 key购买 nike

不知道为什么我的clearRect()在我的“重置”中不起作用。然而它在我的“向上”功能中起作用。 (我的“向上”功能用于清除 Canvas ,然后将图像向上绘制 + 平移 10 像素)

分配是在 Canvas 上创建一个对象,可以通过用户单击按钮来移动该对象。其中一个按钮必须是重置按钮,用于清除 Canvas 并在 Canvas 中心重新绘制图像。

下面是我的代码。应该有 4 个用于运动的函数,但我在这里仅包含“向上”运动函数以提供一般概念:

var surface = document.getElementById("drawingSurface");
var ctx = surface.getContext("2d");

var reset = function () {
alert("Testing"); // <--- This works
ctx.clearRect(0, 0, 499, 499); // <--- But this is not working

ctx.beginPath();
ctx.strokeRect(200, 200, 100, 100);//Face
ctx.fillRect(220, 225, 15, 15);//Left eye
ctx.fillRect(265, 225, 15, 15);//Right eye
ctx.fillRect(245, 250, 10, 10); // Nose
ctx.fillRect(210, 185, 20, 15); // Left ear
ctx.fillRect(270, 185, 20, 15); // Left ear
ctx.closePath();
};

var up = function () {
ctx.clearRect(0, 0, 499, 499);

ctx.beginPath();
ctx.translate(0, -10);
ctx.strokeRect(200, 200, 100, 100);//Face
ctx.fillRect(220, 225, 15, 15);//Left eye
ctx.fillRect(265, 225, 15, 15);//Right eye
ctx.fillRect(245, 250, 10, 10); // Nose
ctx.fillRect(210, 185, 20, 15); // Left ear
ctx.fillRect(270, 185, 20, 15); // Left ear
ctx.closePath();
};

这是我的 HTML:

<canvas id="drawingSurface" width="500" height="500" style="border: 1px    
solid black; background-color: #FFF;">Cat</canvas>
<br>
<button onclick="reset();">RESET</button>
<button onclick="up();">MOVE UP</button>
<button onclick="left();">MOVE LEFT</button>
<button onclick="right();">MOVE RIGHT</button>
<button onclick="down();">MOVE DOWN</button>

最佳答案

我认为问题在于 up 中应用的翻译正在坚持。所以clear正在触发,但随后立即重新绘制相同的图像(尝试注释掉 reset 中的绘制函数)。

要重置翻译,您可以使用 ctx.setTransform(1, 0, 0, 1, 0, 0); ,将其放置在reset中绘图调用之前的某个位置.

关于javascript - html5 Canvas : clearRect() not working inside function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40350919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com