当我尝试在画布上绘制一个带有css预加载图像的图像时,如下所示:
img.style.backgroundColor="red";
ctx.drawImage(img,0,0,100,100);
我发现在没有css的情况下,图像是按照原来的样子绘制的。HTML画布支持css吗?如果不是,有没有办法只在不透明的像素上用一种颜色覆盖透明的png?
发布于 2018-09-05 06:38:28
通过分析绘制图像的每个像素,然后用所需的颜色覆盖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数组并使用函数的后半部分在屏幕上再次绘制该数组来克服这个问题。
发布于 2018-07-05 01:24:45
你能详细说明我们的要求吗?
您不能设置将直接从画布绘制的图像的背景颜色。如果更改颜色,它将反映在源图像中。
您必须从源元素中创建它。如果你想用一些颜色填充方框大小,你可以在绘制之前使用ctx的fillStyle
。
发布于 2018-07-05 02:25:36
看看w3schools上的示例,它将引导您开始如何加载图像并将其复制到画布中。如果您不需要在页面上显示原始图像,那么将'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);
};
https://stackoverflow.com/questions/51178094
复制相似问题