JS绘制叠加图片

米游社活动要求:合影卡 + 自选背景(含角色瓦雷莎)。

合影卡

自选背景

难点

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>

效果图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值