javascript - html5画布编辑图片问题
ringa_lee
ringa_lee 2017-04-11 13:01:55
0
1
385

就是上传图片,然后预览生成data:image/jpg...那样路径的图片。应该是html5生成的。
然后想在这个图片下面加个文字,然后再生成图片出来。
想问怎么做?有实例参考好哈,谢谢了!

ringa_lee
ringa_lee

ringa_lee

membalas semua(1)
小葫芦

实现思路:base64Image -> 导入canvas -> 添加水印 -> 生成base64Image

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<fieldset>
    <legend>canvas</legend>
    <canvas id="canvas"></canvas>
</fieldset>
<fieldset>
    <legend>image</legend>
    <img src="http://userimg.yingyonghui.com/head/24/1458708838143/5426424.png-thumb" alt="" id="xxx">
</fieldset>
<script type="text/javascript">
    var canvas = document.getElementById("canvas");
    var context = canvas.getContext("2d");
    canvas.width = 256;
    canvas.height = 256;

    var image = new Image();
    // 引用外部图片,需设置 crossOrigin 属性,否则 toDataURL 调用异常
    image.setAttribute('crossOrigin', 'anonymous');
    image.onload = function (){
        context.drawImage(image, 0, 0);
        context.font = '16px Arial';
        context.fillStyle = '#fff';
        context.fillText('水印文本 - 火影忍者', 105, 245);
        context.beginPath();
        context.lineWidth = 10;
        context.strokeStyle = '#ff5900';
        context.moveTo(0, 0);
        context.lineTo(256, 0);
        context.lineTo(256, 256);
        context.lineTo(0, 256);
        context.lineTo(0, 0);
        context.stroke();
        // 最终生成的图片 base64 字符串
        var base64Image = canvas.toDataURL();
        document.getElementById('xxx').src = base64Image;
//         console.log(base64Image);
    };
    // 将 src 换成 base64 字符串
    image.src = 'http://userimg.yingyonghui.com/head/24/1458708838143/5426424.png-thumb';
</script>
</body>
</html>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!