使用CSS可以设置img的位置和不透明度,那么为什么要使用canvas标签呢?A:使用多个画布似乎没有影响,但是我们只在每个画布上显示1张图片,B如果它提供了您想要的输出,那么可以使用,但是我会坚持使用一个画布。
示例1使用一个画布:https://jsfiddle.net/CanvasCode/jae7snxh/
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var image1 = new Image();
image1.src = "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQRsJ_wNvd0PfISyPZ5a_QI3Dpeo0g4T5Tuk-R26JXPxfhyFxBTVQ";
var image2 = new Image();
image2.src = "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQQqnYE7Xtre5W0seeFETl00OPSGoujI6xUOHr18GzB4hJE5bCIaQ";
var image3 = new Image();
image3.src = "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRkg3mvI5DwGqG9AUmOEVU6bDDQgM6fT7nQKr8D7XwbQ59lxDiVlA";
context.fillStyle = "#FF0000";
context.fillRect(0,0,500,400);
context.save();
context.globalAlpha = 0.8;
context.drawImage(image1, 0, 0);
context.globalAlpha = 0.3;
context.drawImage(image2, 0, 0);
context.globalAlpha = 0.5;
context.drawImage(image3, 0, 0);
context.restore();
Chrome网络显示需要334毫秒
多画布示例:https://jsfiddle.net/CanvasCode/jae7snxh/3/
var canvas1 = document.getElementById('canvas1');
var context1 = canvas1.getContext('2d');
var canvas2 = document.getElementById('canvas2');
var context2 = canvas2.getContext('2d');
var canvas3 = document.getElementById('canvas3');
var context3 = canvas3.getContext('2d');
var image1 = new Image();
image1.src = "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQRsJ_wNvd0PfISyPZ5a_QI3Dpeo0g4T5Tuk-R26JXPxfhyFxBTVQ";
var image2 = new Image();
image2.src = "https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQQqnYE7Xtre5W0seeFETl00OPSGoujI6xUOHr18GzB4hJE5bCIaQ";
var image3 = new Image();
image3.src = "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcRkg3mvI5DwGqG9AUmOEVU6bDDQgM6fT7nQKr8D7XwbQ59lxDiVlA";
context1.globalAlpha = 0.8;
context1.drawImage(image1, 0, 0);
context2.globalAlpha = 0.3;
context2.drawImage(image2, 0, 0);
context3.globalAlpha = 0.5;
context3.drawImage(image3, 0, 0);
Chrome 网络显示需要 334 毫秒