gpt4 book ai didi

javascript - clearRect 后 Canvas 移动阴影

转载 作者:行者123 更新时间:2023-11-30 16:35:23 25 4
gpt4 key购买 nike

我是 HTML5 新手,开始学习 Canvas 。

目前,我正在使用 Canvas 使一些对象旋转。我创建的矩形确实会移动,但是,我遇到了一个问题,在对象移动后,一些阴影仍然存在,正如您从我捕获的图像中看到的那样。

enter image description here

我只想要矩形,不包括蓝色背景笨拙的东西。我尝试使用不同的浏览器来查看此 HTML5 文档,但出现了同样的问题。是我电脑的问题,还是代码的问题?如果是这样,我该如何解决?

我还在 jsFiddle 中附上了旋转矩形示例的源代码:http://jsfiddle.net/hphchan/ogoj9odf/1/

这是我的关键代码:

在 JavaScript 中:

function canvaScript() {
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

context.translate(200, 200); // fix the origin as center of the canvas
rotating(context);
}

function rotating(context) {
context.clearRect(-50, -100, 100, 200); // why boundaries, shadows exist??
context.rotate(Math.PI/180);
context.fillStyle = '#0000FF';
context.fillRect(-50, -100, 100, 200);

setTimeout(function() {rotating(context)}, 100);
}

在 HTML 中

<body onload="canvaScript()">
<canvas id="myCanvas" width="400" height="400"></canvas>
</body>

感谢您的回答。

最佳答案

这个问题可能来自抗锯齿。

画完旋转后直接清除就可以看到了:

function canvaScript() {
var context = canvas.getContext('2d');

context.translate(200, 200); // fix the origin as center of the canvas
context.rotate(Math.PI/4);
rotating(context);
}

function rotating(context) {
context.fillStyle = '#0000FF';
context.fillRect(-50, -100, 100, 200);
context.clearRect(-50, -100, 100, 200);
}

canvaScript();
<canvas id="canvas" width="400" height="400"></canvas>

因此解决此问题的一种解决方案是清除比您刚刚绘制的矩形稍大的 clearRect

function canvaScript() {
var context = canvas.getContext('2d');

context.translate(200, 200); // fix the origin as center of the canvas
rotating(context);
}

function rotating(context) {
// clear one extra pixel in all directions
context.clearRect(-51, -101, 102, 202);
context.rotate(Math.PI/180);
context.fillStyle = '#0000FF';
context.fillRect(-50, -100, 100, 200);

setTimeout(function() {rotating(context)}, 100);
}

canvaScript();
<canvas id="canvas" width="400" height="400"></canvas>

关于javascript - clearRect 后 Canvas 移动阴影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32772127/

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