当我尝试使用带有css的预加载图像在画布上绘制图像时:
img.style.backgroundColor="red";
ctx.drawImage(img,0,0,100,100);
我发现正在绘制的图像没有css就会出现。 HTML画布是否支持CSS?如果没有,是否有办法用透明度覆盖png,只在不透明的像素上涂上颜色?
你能详细说明我们的要求吗?
您无法设置将直接从画布绘制的图像的背景颜色。如果改变颜色,它将反映在源图像中。
你必须从源元素中创建它。如果你想用一些颜色填充盒子大小,你可以在绘制之前使用ctx的fillStyle
。
看一下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);
};
画布不会渲染css,无论你用什么css为图像它总是渲染普通图像,除非你自己绘制边框或背景
通过分析绘制图像的每个像素,然后覆盖具有所需颜色的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数组并使用函数的后半部分再次在屏幕上绘制数组来克服。