米游社活动要求:合影卡 + 自选背景(含角色瓦雷莎)。
合影卡
自选背景
难点
1.闭包
2.循环 & 判断所有图片加载完成
3.img增加wh字段定为canvas高宽
js获取标签元素data-*属性值的4种方法_javascript技巧_脚本之家
img.setAttribute('data-wh', 'wh');
if (img.dataset.wh == 'wh') { }
代码
<html>
<head>
<title>叠图</title>
<style>
h1 { text-align:center; }
a { text-decoration:none; }
p { text-indent:2em; }
</style>
</head>
<body>
<textarea id="textarea">
瓦雷莎.jpg
合影卡.png;wh</textarea> <button id="button_draw">绘图</button><br><br>
<canvas id="canvas"></canvas>
<script>
var ctx = canvas.getContext('2d');
var list = new Array();
function load() {
//var w=0, h=0;
var s = textarea.value.trim();
//console.log(s);
var sl = s.split('\n');
//console.log(sl);
list.length = 0;
for (i=0; i<sl.length; i++) {
var img = new Image();
var sl1 = sl[i].split(';');
img.src = sl1[0];
if (sl1.length > 0)
if (sl1[1] == 'wh')
img.setAttribute('data-wh', 'wh');
console.log(img);
list.push(img);
(function(img, list){
img.onload = function(){
console.log(img, img.dataset.wh, img.dataset.wh == 'wh', img.width, img.height);
if (img.dataset.wh == 'wh') {
canvas.width = img.width;
canvas.height = img.height;
}
var b = true;
for (j=0; j<list.length; j++) {
b = b & list[j].complete;
//console.log(list[j], list[j].complete, b);
}
if (b) {
draw();
}
}
})(img, list);
}
}
function draw() {
for (i=0; i<list.length; i++) {
ctx.drawImage(list[i],0,0);
}
}
button_draw.onclick = function() {
load();
}
</script>
</body>
</html>
效果图