用文本预渲染画布矩形,就是这种糟糕的性能

Pre-rendering a canvas rectangle with text, is this bad performance?

本文关键字:性能 文本 布矩形      更新时间:2023-09-26
完成最多

需要 0.300 毫秒,这比在没有预渲染的情况下直接计算函数至少慢 2 倍,我认为这是相当多的......你们怎么看?这正常吗?我这样做对吗?一定是出了什么问题。

function complexDraw(ctx){
    ctx.fillStyle = "Black";
    ctx.fillRect(90 * Xf, 380 * Yf, 200 * Xf, 30 * Yf);//k10
    ctx.fillStyle = "White";
    ctx.font = pixels + "px monospace";
    ctx.textAlign = "center";
    ctx.fillText("Left: " + currentremain, 185 * Xf, 400 * Yf);
}
function cloneCanvas(oldCanvas) {
    //create a new canvas
    var newCanvas = document.createElement('canvas');
    var context = newCanvas.getContext('2d');
    //set dimensions
    newCanvas.width = oldCanvas.width;
    newCanvas.height = oldCanvas.height;
    //apply the old canvas to the new one
    context.drawImage(oldCanvas, 0, 0);
    //return the new canvas
    return newCanvas;
}
var cacheCanvas = cloneCanvas(a_canvas); // newCanvas
var cacheCtx = cacheCanvas.getContext('2d'); // context

var draw = function draw(){
    complexDraw(cacheCtx); //updates text each time
    ctx.drawImage(cacheCanvas,0,0);
}
console.time("new");
draw();
console.timeEnd("new")// 0.300ms

您仍在"缓存"画布上绘制绘图,因此本质上您正在绘制 + 复制。如果它需要更多而不是直接绘画,我不会感到惊讶。特别是如果您的画布很大并且您必须复制大量像素。

编辑:澄清一下:您不需要为 HTML 画布实现双重缓冲,因为浏览器在脚本完成执行之前不会更新屏幕上的画布图像。