HTML 5 canvas 绘图图像未显示 css

HTML 5 canvas drawing image not showing css

当我尝试在 canvas 上使用预加载图像 css 绘制图像时,例如:

img.style.backgroundColor="red";
ctx.drawImage(img,0,0,100,100);

我发现正在绘制图像,就像没有 css 时一样。 HTML canvas 支持 css 吗?如果没有,有没有一种方法可以只在不透明的像素上覆盖带有颜色的透明 png?

您能否详细说明我们的要求?

您无法设置要直接从 canvas 绘制的图像的背景颜色。如果您更改颜色,它将反映在源图像中。

你必须从源元素开始。如果你想用一些颜色填充框大小,你可以使用 fillStyle of the ctx before draw.

查看 w3schools 上的示例,了解如何加载图像并将其复制到 canvas。如果您不需要在页面上显示原始图像,请将 'style="display:none;"' 添加到 img 标签。要为图像着色,请结合填充的矩形查看 globalAlpha - 遵循以下原则:

window.onload = function() {
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");
    var img = document.getElementById("scream");

    ctx.globalAlpha = 0.5;
    ctx.beginPath();
    ctx.rect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = "#ff0000";
    ctx.fill();

    ctx.drawImage(img, 10, 10);
};

Canvas 不渲染 css 无论你使用什么图像 css 它总是渲染纯图像,除非你自己绘制边框或背景

通过分析绘制图像的每个像素,然后用所需颜色覆盖 1x1 矩形,可以覆盖在 canvas 上绘制的图像。以下是如何执行此操作的示例:

function overlayColor(img,x,y,a,r,g,b,drawWidth,drawHeight){
    //create a canvas in memory and draw the image there to analyze it
    var tmpCanvas = document.createElement('canvas');
    var context = tmpCanvas.getContext('2d');
    tmpCanvas.width = drawWidth;
    tmpCanvas.height = drawHeight;
    context.drawImage(img,0,0,drawWidth,drawHeight);
    let pData = new Array();
    for (let i = 0; i < tmpCanvas.width; i++){
        for (let j = 0; j < tmpCanvas.height; j++){
            if (context.getImageData(i, j, 1, 1).data[3] != 0){//if the pixel is not transparent then add the coordinates to the array
                pData.push([i,j]);
            }
        }
    }
    //then every pixel that wasn't transparent will be overlayed with a 1x1 rectangle of the inputted color 
    //drawn at the (x,y) origin which was also given by the user
    //this uses ctx, the context of the canvas visible to the user
    ctx.fillStyle="rgba(" + r + "," + g + "," + b + "," + a + ")";
    for (let i = 0; i < pData.length; i++){
        ctx.fillRect(x + pData[i][0],y + pData[i][1],1,1);
    }

}

由于该函数采用 x 和 y 值,因此将对用户提供的图像进行分析,并仅覆盖在用户提供的坐标处不透明的像素上,同时还提供了 rgba 值。我发现这个过程可能会导致一些延迟,但可以通过保存 pData 数组并使用函数的后半部分再次在屏幕上绘制数组来克服。