我发现这段代码可以在 Canvas 上绘制。在 firefox 中它工作正常但在最新的 Chrome 中缺乏性能。如果鼠标移动得非常快,则在 Chrome 中绘制的线位于光标后面。为什么?
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var width = window.innerWidth;
var height = window.innerHeight;
canvas.height = height;
canvas.width = width;
canvas.addEventListener('mousedown', function(e) {
this.down = true;
this.X = e.pageX ;
this.Y = e.pageY ;
this.color = rgb();
}, 0);
canvas.addEventListener('mouseup', function() {
this.down = false;
}, 0);
canvas.addEventListener('mousemove', function(e) {
if(this.down) {
with(ctx) {
beginPath();
moveTo(this.X, this.Y);
lineTo(e.pageX , e.pageY );
strokeStyle = "rgb(0,0,0)";
ctx.lineWidth=3;
stroke();
}
this.X = e.pageX ;
this.Y = e.pageY ;
}
}, 0);
最佳答案
javascript在每个浏览器中的执行速度是不同的,所以它可以在firefox中运行得更好。这也取决于您自己的 PC 性能。
with
语句也会减慢执行速度。
这是因为 with() 将一组额外的变量附加到上述作用域链的开头。这个额外的项目意味着无论何时调用任何变量,Javascript 引擎都必须循环遍历 with() 变量,然后是局部变量,然后是全局变量。
因此 with() 本质上给局部变量带来了全局变量的所有性能缺陷,进而破坏了 Javascript 优化。
这个为什么不使用with
的解释来自here
关于javascript - HTML5 Canvas 在 Firefox 上比在 Chrome 上更快!为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17638802/