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

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

问题描述

如果我快速连续画到画布上,例如。一个环境中的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.

要绘制更改并在屏幕上查看结果,使用 setInterval setTimeout 来控制回浏览器,但要求在将来的某个时间运行代码。

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);

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

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