如何在画布中强制显示更新 [英] how to force a display update in canvas

查看:32
本文介绍了如何在画布中强制显示更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我快速连续地在画布上绘制很多,例如循环中的 context.fillRect,浏览器似乎要等到循环完成后再显示任何绘图(可能通过双缓冲)

if I draw to the canvas a lot in quick succession, e.g. a context.fillRect in a loop, browsers seem to wait until the loop has finished before any of the drawing is displayed (possibly via double-buffering)

有没有办法强制浏览器在每次绘制操作后显式或隐式更新显示?

Is there any way to force the browser to update the display, either explicitly or implicitly after each draw operation?

推荐答案

实际上并不是因为任何双缓冲导致您看不到结果,而是因为 Web 浏览器中的 JavaScript 是单线程的.如果您类似地在 JavaScript 中创建一个循环,重复执行诸如 myDiv.style.top = parseInt(myDiv.style.top) + 1 +"px"; 之类的操作,您将看到什么都不会明显改变在浏览器中——甚至在几秒钟内——直到你的 JavaScript 完成执行.

It is not really because of any double-buffering that you don't see the results, but rather because JavaScript in the web browser is single-threaded. If you similarly create a single loop in JavaScript that repeatedly does something like myDiv.style.top = parseInt(myDiv.style.top) + 1 +"px"; you will see that nothing will visibly change in the browser—even over many seconds—until your JavaScript has finished executing.

要绘制更改并在屏幕上查看结果,您需要使用 setIntervalsetTimeout 将控制权交还给浏览器,但要求在某个时间运行代码未来.

To draw changes and see the results on the screen, you need to use setInterval or setTimeout to yield control back to the browser but ask to run code at some point in the future.

例如,以每秒 15 次的速度在画布上绘制一个新的随机、随机着色的矩形:

For example, to draw a new random, randomly-colored rectangle on the canvas 15 times a second:

var canvas = document.getElementsByTagName('canvas')[0];
var ctx = canvas.getContext('2d');
setInterval(function(){
  ctx.clearRect(0,0,canvas.width,canvas.height);
  var r=Math.random()*255, g=Math.random()*255, b=Math.random()*255;
  ctx.fillStyle = 'rgb('+r+','+g+','+b+')';
  var w=Math.random()*canvas.width,     h=Math.random()*canvas.height;
  var x=Math.random()*(canvas.width-w), y=Math.random()*(canvas.height-h);
  ctx.fillRect(x,y,w,h);
},1000/15);

这篇关于如何在画布中强制显示更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆