HTML 5 Canvas绘图图像未显示CSS

时间:2018-07-04 16:47:24

标签: javascript css html5 canvas transparency

当我尝试在画布上绘制带有css这样的预加载图像的图像时:

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

我发现图像正在绘制,就像没有css一样。 HTML canvas是否支持CSS?如果不是,是否有办法只在不透明的像素上用透明颜色覆盖png?

4 个答案:

答案 0 :(得分:0)

您可以详细说明我们的要求吗?

您不能设置将直接从画布上绘制的图像的背景颜色。如果您更改颜色,它将反映在源图像中。

您必须从源元素中进行制作。如果要用某种颜色填充框的大小,可以在绘制前使用ctx的fillStyle

答案 1 :(得分:0)

w3schools上查看示例,该示例将使您开始如何加载图像并将其复制到画布中。如果您不需要在页面上显示原始图像,则在img标签中添加'style =“ display:none;”'。要着色图像,请结合填充矩形查看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);
};

答案 2 :(得分:0)

无论您使用哪种CSS图像,画布都不会渲染CSS,除非您自己绘制边框或背景,否则它将始终呈现纯图像

答案 3 :(得分:0)

可以通过分析绘制图像的每个像素来覆盖画布上绘制的图像,然后用所需的颜色覆盖1x1矩形。这是一个这样做的例子:

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数组并使用该函数的后半部分在屏幕上再次绘制该数组来克服。