欧美一区二区三区,国内熟女精品熟女A片视频小说,日本av网,小鲜肉男男GAY做受XXX网站

canvas如何提高作圖性能

錢琪琛2年前26瀏覽0評論

canvas如何提高作圖性能?

提高畫圖的性能,你需要了解以下幾點:

1、預渲染

錯誤代碼:

var canvas = document.getElementById("myCanvas");

var context = this.canvas.getContext('2d');

var drawAsync = eval(Jscex.compile("async", function () {

while (true) {

drawMario(context);

$await(Jscex.Async.sleep(1000));

}

}))

drawAsync().start();

正確代碼:

var canvas = document.getElementById("myCanvas");

var context = this.canvas.getContext('2d');

var m_canvas = document.createElement('canvas');

m_canvas.width = 64;

m_canvas.height = 64;

var m_context = m_canvas.getContext('2d');

drawMario(m_context);

var drawAsync = eval(Jscex.compile("async", function () {

while (true) {

context.drawImage(m_canvas, 0, 0);

$await(Jscex.Async.sleep(1000));

}

}))

drawAsync().start();

2、盡量少調用canvasAPI

錯誤代碼:

for (var i = 0; i < points.length - 1; i++) {

var p1 = points[i];

var p2 = points[i + 1];

context.beginPath();

context.moveTo(p1.x, p1.y);

context.lineTo(p2.x, p2.y);

context.stroke();

}

正確代碼:

context.beginPath();

for (var i = 0; i < points.length - 1; i++) {

var p1 = points[i];

var p2 = points[i + 1];

context.moveTo(p1.x, p1.y);

context.lineTo(p2.x, p2.y);

}

context.stroke();

3、盡量少改變canvas的狀態

錯誤代碼:

for (var i = 0; i < STRIPES; i++) {

context.fillStyle = (i % 2 ? COLOR1 : COLOR2);

context.fillRect(i * GAP, 0, GAP, 480);

}

正確代碼:

context.fillStyle = COLOR1;

for (var i = 0; i < STRIPES / 2; i++) {

context.fillRect((i * 2) * GAP, 0, GAP, 480);

}

context.fillStyle = COLOR2;

for (var i = 0; i < STRIPES / 2; i++) {

context.fillRect((i * 2 + 1) * GAP, 0, GAP, 480);

}

4、重新渲染的范圍盡量小

錯誤代碼:

context.fillRect(0, 0, canvas.width, canvas.height);

正確代碼:

context.fillRect(20, 20, 100, 100);

5、復雜場景使用多層畫布

<canvas width="600" height="400" style="position: absolute; z-index: 0">

</canvas>

<canvas width="600" height="400" style="position: absolute; z-index: 1">

</canvas>

6、不要使用陰影

context.shadowOffsetX = 5;

context.shadowOffsetY = 5;

context.shadowBlur = 4;

context.shadowColor = 'rgba(255, 0, 0, 0.5)';

context.fillRect(20, 20, 150, 100);

7、清除畫布

一般情況下:clearRect的性能優于fillRect優于canvas.width = canvas.width;

8、像素級別操作盡量用整數

9、使用Jscex制作動畫效果

var drawAsync = eval(Jscex.compile("async", function () {

while (true) {

context.drawImage(m_canvas, 0, 0);

$await(Jscex.Async.sleep(1000));

}

}))

drawAsync().start();

10、其它

與渲染無關的計算交給worker,復雜的計算交給引擎(自己寫,或者用開源的),比如3D、物理。緩存load好的圖片,canvas上畫canvas,而不是畫image。

自己多積累經驗,使程序運行的消耗減少到最小就好的。

java畫圖開源,canvas如何提高作圖性能