首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >HTML 5画布绘图图像未显示css

HTML 5画布绘图图像未显示css
EN

Stack Overflow用户
提问于 2018-07-05 00:47:24
回答 4查看 256关注 0票数 0

当我尝试在画布上绘制一个带有css预加载图像的图像时,如下所示:

代码语言:javascript
复制
img.style.backgroundColor="red";
ctx.drawImage(img,0,0,100,100);

我发现在没有css的情况下,图像是按照原来的样子绘制的。HTML画布支持css吗?如果不是,有没有办法只在不透明的像素上用一种颜色覆盖透明的png?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2018-09-05 06:38:28

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

代码语言:javascript
复制
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数组并使用函数的后半部分在屏幕上再次绘制该数组来克服这个问题。

票数 0
EN

Stack Overflow用户

发布于 2018-07-05 01:24:45

你能详细说明我们的要求吗?

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

您必须从源元素中创建它。如果你想用一些颜色填充方框大小,你可以在绘制之前使用ctx的fillStyle

票数 0
EN

Stack Overflow用户

发布于 2018-07-05 02:25:36

看看w3schools上的示例,它将引导您开始如何加载图像并将其复制到画布中。如果您不需要在页面上显示原始图像,那么将'style="display:none;"‘添加到img标记中。要对图像进行着色,可以看看globalAlpha与填充的矩形的组合-沿着这些线的东西:

代码语言:javascript
复制
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);
};
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51178094

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档