完整代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Canvas 图片生成示例</title>
<style>
canvas {
display: block;
margin: 20px auto;
}
</style>
</head>
<body>
<canvas id="canvas" width="600" height="360"></canvas>
<button id="downloadBtn">下载图片</button>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// 绘制渐变背景
var gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
gradient.addColorStop(0, 'rgb(48, 120, 238)');
gradient.addColorStop(1, 'rgb(141, 44, 254)');
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 绘制logo
var logoImg = new Image();
logoImg.src = "/images/logo_light.png";
logoImg.onload = function() {
var logoWidth = 120; // 设定logo宽度为100px
var logoHeight = logoWidth * (logoImg.height / logoImg.width); // 根据宽度等比例缩放高度
ctx.drawImage(logoImg, 0, 10, logoWidth, logoHeight);
};
// 随机生成小星星和光斑
function randomStars() {
var starCount = 50;
for (var i = 0; i < starCount; i++) {
var x = Math.random() * canvas.width;
var y = Math.random() * canvas.height;
var radius = Math.random() * 2;
ctx.beginPath();
ctx.fillStyle = '#ffffff';
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.fill();
}
}
randomStars();
// 绘制文字
ctx.fillStyle = '#ffffff';
ctx.font = '36px Microsoft YaHei';
ctx.textAlign = "center";
var texts = ["首届中国国际供应链促进博览会", "北京·2023年12月"];
var fontSize = 36;
var lineHeight = 52;
var textStartY = canvas.height / 2 - lineHeight * 0.5;
// 第一行文字
ctx.fillText(texts[0], canvas.width / 2, textStartY);
// 第二行文字
ctx.font = '14px Microsoft YaHei';
ctx.fillText(texts[1], canvas.width / 2, textStartY + lineHeight);
document.getElementById('downloadBtn').addEventListener('click', function() {
var timestamp = Date.parse(new Date());
canvas.toDataURL("image/png").then(function(dataURL) {
var link = document.createElement("a");
link.href = dataURL;
link.download = "cover_" + timestamp + ".png";
link.click();
});
});
</script>
</body>
</html>
复制保存为html即可预览效果。