Canvas教程:拼图,组合图像,画圆形图像,添加二维码logo,添加文字
1,创建canvas对象
// method 1 document.createElement('canvas') // method 2 <canvas id="canvas" /> document.getElementById('canvas')
2,设置大小并初始化上下文
canvas.width = 341; canvas.height = 512; var ctx = canvas.getContext('2d');
3,在canvas上面添加文字,若有图像,最后添加文字,避免被覆盖
ctx.font = 'bold 20px Arial'; ctx.fillStyle = '#058'; ctx.fillText('我爱你', 150, 180); ctx.strokeStyle = 'rgba(255,255,255,0.4)'; ctx.strokeText('我爱你', 150, 180);
4,添加背景图像
var img = new Image(); img.src = 'bg.jpg'; img.onload = function() { var width = img.width / 2; var height = img.height / 2; // 背景图像加载后画到canvas画布上 ctx.drawImage(img, 0, 0, width, height); }
5,添加二维码图像即组图
// https://github.com/davidshimjs/qrcodejs <div id="qrcode" style="display: none"></div> new QRCode($('qrcode'), { text: 'http://qiaolevip.iteye.com', width: 128, height: 128, colorDark : '#000000', colorLight : '#ffffff', correctLevel : QRCode.CorrectLevel.H }); var img = $('qrcode').querySelector('img'); // 二维码图像画到canvas画布上 ctx.drawImage(img, 0, 0, width, height);
6,logo叠加添加到二维码上面即组图
var img = new Image(); img.src = 'logo.jpg'; img.onload = function() { var width = img.width / 2; var height = img.height / 2; // 背景图像加载后画到canvas画布上 ctx.drawImage(img, 0, 0, width, height); }
7,绘制圆形logo图像
ctx.save(); // 保存当前ctx的状态 ctx.arc(x+a/2, y+a/2, a/2, 0, 2 * Math.PI); //画出圆 ctx.clip(); ctx.drawImage(img, x, y, a, b); // 在刚刚裁剪的园上画图 ctx.restore(); // 还原状态
8,最终效果图呈现形式:
更多实例应用扫码体验:
相关推荐
Allinputs 2020-08-30
Steven 2020-08-07
风萧萧梦潇 2020-07-30
small 2020-07-29
无缘公子 2020-06-28
wangdaren 2020-06-03
Develop 2020-06-01
zhaoyangjian 2020-05-26
gufudhn 2020-05-02
hgzhang 2020-04-23
yiyilanmei 2020-04-22
caishancai 2020-04-22
xieyixiao 2020-04-22
zcabcd 2020-04-18
cdkey 2020-04-17
D先生 2020-04-14
jiamingku 2020-04-10
85580695 2020-04-07
woniulx0 2020-03-26