画布预渲染

Canvas pre rendering?

本文关键字:布预渲      更新时间:2023-09-26

在画布上预渲染图像是否有任何意义?

,

var img; // Img object
var pre = document.createElement("canvas");
pre.width = img.width;
pre.height = img.height;
var precon = pre.getContext("2d");
precon.drawImage(img, 0, 0);
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
for(var i =0; i < 10000; ++i) {
    ctx.drawImage(pre, Math.random() * canvas.width, Math.random() * canvas.height);
}

我没有看到点,因为你仍然调用context.drawImage不管你做什么,除非画布api更快地从画布对象而不是图像对象绘制图像?

首先,我必须说你的例子不适合强调画布预渲染的需要和好处。

我给你一个更好的例子,你需要在画布上多次绘制需要大量计算的东西。

假设你有这个draw函数:

function complexDraw(ctx){
    ctx.drawImage(img, width, height);
    // heavy computation goes here
    // some transforms maybe
    ctx.ctx.setTransform(-1, 0, 0, 1, 200, 200);   
    ctx.fillStyle = "rgba(100, 100, 255, 0.5)";   
    ctx.fillRect(50, 50, 100, 100); 
    //maybe draw another img/video/canvas
    ctx.drawImage(anotherImg, width, height);
    // ...
}
function draw(){
    complexDraw(ctx);
}

现在假设你也想在画布上显示当前时间。这意味着我们将在draw函数的底部添加以下内容:

function drawTime(ctx){
    ctx.fillText(new Date().getTime(), 10, 50); 
}

现在我们的绘制函数是这样的:

function draw(){
    complexDraw(ctx);
    drawTime(ctx);
}

由于您希望始终显示当前时间,因此需要每秒调用draw函数:

setInterval(draw, 1000);

这实际上意味着你每秒钟都在做一些繁重的计算,只是为了更新一个愚蠢的小文本。

如果有一种方法可以拆分draw函数,只计算需要计算的东西(那些变化的东西)……但有:说你好,画布预渲染!

关键思想是在单独的画布上绘制不改变的部分(并且不需要重新计算)-让我们称之为cacheCanvas -并且每当我们想要重新绘制东西时,只需将其内容复制到我们的应用程序画布上:

// suppose we have a `clone` function
var cacheCanvas = clone(canvas),
    cacheCtx = cacheCanvas.getContext('2d');
// let's draw our complex stuff on the cacheCanvas
complexDraw(cacheCtx);
// modify our main `draw` function to copy the result of the `complexDraw`
// function, not to call it
function draw(){
    ctx.drawImage(cacheCanvas, width, height);
    drawTime();
}

现在我们基本上每秒重新绘制整个画布,但我们不会重新计算complexDraw中所有繁重的工作。

我只是想指出,大多数基于画布的游戏不能以60fps(每秒重画60次)运行,如果没有使用预渲染或另一种称为画布分层的技术来提高性能

(这也值得研究)。