我一直难以在我的 Canvas 上生成清晰的形状,我一直在取出代码来尝试调试它,似乎原因之一是正在重绘。下面是没有循环的代码:
var context = $('canvas')[0].getContext('2d');
function draw() {
context.clearRect(0, 0, context.width, context.height);
context.beginPath();
context.arc(100, 100, 50, 0, 2 * Math.PI, false);
context.fillStyle = 'red';
context.fill();
context.lineWidth = 4;
context.strokeStyle = 'darkred';
context.stroke();
}
draw();
<canvas width=200 height=200></canvas>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
循环也是一样的:
var context = $('canvas')[0].getContext('2d');
function draw() {
requestAnimationFrame(draw);
context.clearRect(0, 0, context.width, context.height);
context.beginPath();
context.arc(100, 100, 50, 0, 2 * Math.PI, false);
context.fillStyle = 'red';
context.fill();
context.lineWidth = 4;
context.strokeStyle = 'darkred';
context.stroke();
}
function init() {
if (typeof game_loop != "undefined") clearInterval(game_loop);
var game_loop = setInterval(draw, 30);
}
init();
<canvas width=200 height=200></canvas>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
对于那些看不到我在 Chrome 中所做的事情的人,这里有一张图片:
似乎即使将 requestAnimationFrame(draw);
这行放在第一个示例中也会导致同样的问题。
我在这里做错了什么?
最佳答案
问题是您无法访问 context.width
和 context.height
。因此,这将导致 clearRect
方法失败,并在另一个圆上绘制圆。
使用 canvas.width
和 canvas.height
。
var canvas = $('canvas')[0]
var context = canvas.getContext('2d');
var game_loop
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.arc(100, 100, 50, 0, 2 * Math.PI, false);
context.fillStyle = 'red';
context.fill();
context.lineWidth = 4;
context.strokeStyle = 'darkred';
context.stroke();
}
function init() {
if (typeof game_loop != "undefined") clearInterval(game_loop);
game_loop = setInterval(requestAnimationFrame.bind(null, draw), 30) // use requestAnimationFrame but limit to 30ms interval - from @JoshuaK
}
init();
<canvas width=200 height=200></canvas>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
您还同时使用了间隔和 requestAnimationFrame
。这将导致巨大的滞后。仅当您别无选择时才使用动画间隔。你也可以使用这个 polyfill:
window.requestAnimFrame = function(){
return (
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(func){
window.setTimeout(func, 30);
}
);
}()
关于javascript - 为什么重绘循环会给我的 HTML5 Canvas 起别名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47046501/