小程序生成海報(bào),在小程序端是很容易實(shí)現(xiàn),不過最近遇到一個需要在后臺實(shí)現(xiàn)海報(bào)生成的需求,就研究了一下html2canvas生成海報(bào)的方法
需求
在后臺商品列表,點(diǎn)擊推廣,生成包含商品圖片和小程序碼的推廣海報(bào),商品圖片存放在阿里云oss,存在跨域問題
實(shí)現(xiàn)
<-- 小程序碼在服務(wù)端通過小程序sdk獲取后保存在服務(wù)端 -->
<div id="poster">
<div class="goods_pic">
<img src="https://dev.oss-cn-hangzhou.aliyuncs.com/test.png">
</div>
<div id="mini_qrcode">
<img src="https://abc.com/mini.png">
</div>
</div>
<div class="save_btn" @click="savecanvas">
保存圖片
</div>
// 創(chuàng)建并生成海報(bào)
function savecanvas() {
var shareContent = $('#poster')[0]; // dom對象
var width = shareContent.offsetWidth; //獲取dom 寬度
var height = shareContent.offsetHeight; //獲取dom 高度
var canvas = document.createElement("canvas");
var scale = 1; //定義任意放大倍數(shù) 支持小數(shù)
canvas.width = width * scale; //定義canvas 寬度 * 縮放
canvas.height = height * scale; //定義canvas高度 *縮放
canvas.style.width = width * scale + 'px';
canvas.style.height = height * scale + 'px';
canvas.getContext("2d").scale(scale, scale); //獲取context,設(shè)置scale
var opts = {
scale: scale, // 添加的scale 參數(shù)
canvas: canvas, //自定義 canvas
logging: true, //日志開關(guān),便于查看html2canvas的內(nèi)部執(zhí)行流程
width: width, //dom 原始寬度
height: height,
useCORS: true // 【重要】開啟跨域配置
};
html2canvas(shareContent, opts).then(canvas => {
var imgUri = canvas.toDataURL("image/png")
let aLink = document.createElement("a");
aLink.style.display = "none";
aLink.href = imgUri;
aLink.download = "海報(bào)圖片.png";
// 觸發(fā)點(diǎn)擊-然后移除
document.body.appendChild(aLink);
aLink.click();
document.body.removeChild(aLink);
});
};
跨域問題
雖然開啟了 html2canvas 的跨域配置 useCORS,但是生成的海報(bào)商品圖片位置為空,所以考慮替換方案,直接在服務(wù)端獲取圖片的base64內(nèi)容展示在前端
// 使用curl 下載圖片
function curlFileGetContent($url, $path) {
$handler = curl_init();
$fp = fopen($path, 'wb');
curl_setopt($handler, CURLOPT_URL, $url);
curl_setopt($handler, CURLOPT_FILE, $fp);
curl_setopt($handler, CURLOPT_HEADER, 0);
curl_setopt($handler, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($handler, CURLOPT_TIMEOUT, 60);
curl_exec($handler);
curl_close($handler);
fclose($fp);
return $path;
}
// 將圖片轉(zhuǎn)為base64
function base64EncodeImage($image_file) {
$image_info = getimagesize($image_file);
$image_data = fread(fopen($image_file, 'r'), filesize($image_file));
$base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
return $base64_image;
}
以上,解決了html2canvas跨域圖片不顯示的問題
其他方案
后端支持:阿里云 header頭中設(shè)置 Access-Control-Allow-Origin: *