遇到个 需要生成定义海报的功能,觉得有趣就自己写个简单的练习。个人水平有限写的不好勿喷哈哈
原理是 用svg的 foreignObject 标签 定义结构 然后 canvas 把svg画出来。下面上代码
···················································分割线······································································
<body id='body' style="display: flex;justify-content: center;align-items: center;height: 70vh;">
<div id='box' class="box" style="width: 300px;border: 1px solid cadetblue;padding: 15px 15px;">
<img style="width: 300px;" src="1.jpg"/>
<div style="font-size: 22px;color: #333;margin-top: 10px;">年轻人的时代</div>
<div style="display: flex;width: 100%;justify-content: space-between;">
<div style="font-size: 15px;color: #999;margin-top: 10px;">扫码二维码下载掌上英雄联盟</div>
<img style="width: 30%;" src="2.jpg"/>
</div>
</div>
<script type="text/javascript">
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
function getBase64Image(img) {
canvas.width = img.width;
canvas.height = img.height;
ctx.clearRect(0, 0, img.width, img.height);
ctx.drawImage(img, 0, 0, img.width, img.height);
var ext = img.src.substring(img.src.lastIndexOf(".") + 1).toLowerCase();
var dataURL = canvas.toDataURL("image/" + ext);
return dataURL;
}
function draw(img){
let width = img.width, height = img.height;
canvas.width = img.width;
canvas.height = img.height;
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0,img.width,img.height);
// 绘制图片到canvas
ctx.drawImage(img,0,0);
let dataURL = canvas.toDataURL();
return dataURL
};
window.onload = function() {
var body = document.getElementById('body')
var box = document.querySelector('.box');
let all = document.querySelectorAll('img')
for (let item of all) {
let image = new Image();
image.src = item.src;
image.setAttribute('crossOrigin', 'anonymous');
image.onload = function() {
item.setAttribute('src',getBase64Image(image))
}
console.log(item)
}
box.setAttribute('xmlns', 'http://www.w3.org/1999/xhtml');
let img = new Image()
setTimeout(function(){
img.src = 'data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="' + box.offsetWidth + '" height="' + box.offsetHeight + '"><foreignObject x="0" y="0" width="100%" height="100%">'+
new XMLSerializer().serializeToString(box).replace(/#/g, '%23').replace(/\n/g, '%0A') +
'</foreignObject></svg>';
img.onload = function(){
draw(img)
let k = document.createElement('img')
k.setAttribute('src',draw(img))
body.appendChild(k)
}
},0)
}
</script>
</body>
······································遇到的坑·············································
如果svg 里面包含img 直接引用项目地址 或者网络地址可能 导致画出的图片不显示,需要引用base64地址
创建的img 对象 img.src赋值 需要放到img.onload里面加载完 执行画图,
最外层的div 记得 加上xmlns= ‘http://www.w3.org/1999/xhtml’