我想生成由标签和图标组成的图像。标签部分会有很多变化(50-100),而大约有10个图标。我想通过将最终图像分成两部分,即标签图像和图标图像,以模块化方式制作最终图像。我将构建一个服务,返回标签的dataURI,同时图标dataURI将嵌入页面中。然后我想结合这两个不同的dataURI来创建一个表示组合图像的dataURI。
我如何在客户端执行此操作?
答案 0 :(得分:5)
您可以使用数据uris创建图像,然后使用canvas
绘制包含它们的新图像。这是一个简单的例子:
var nloaded = 0;
function checkload(event) {
nloaded++;
if (nloaded < 2) {
return;
}
var canvas = document.querySelector('canvas');
var context = canvas.getContext('2d');
context.drawImage(image1, 0, 0, 50, 50);
context.drawImage(image2, 50, 50, 100, 100);
var combined = new Image;
combined.src = canvas.toDataURL('data/gif');
document.body.appendChild(combined);
}
var image1 = new Image;
image1.onload = checkload;
image1.src = 'data:image/gif;base64,R0lGODdhAgACALMAAAAAAP///wAAAAAAAP8AAAAAAAAAAAAAAAAA/wAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAAAgACAAAEAxBJFAA7';
var image2 = new Image;
image2.onload = checkload;
image2.src = 'data:image/gif;base64,R0lGODdhAgACALMAAAAAAP///wAAAAAAAP8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAAAgACAAAEA5BIEgA7';
canvas {
display: none;
}
<canvas width=100 height=100></canvas>
从数据URI加载图像并使用画布上下文的drawImage
命令组合后,您可以使用画布创建新图像,如:
var combined = new Image;
combined.src = canvas.toDataURL('data/gif');
不幸的是,这在IE8中不起作用。
答案 1 :(得分:1)
使用包含URI src和x,y偏移的图像对象数组的示例:
var images = [
{ src: 'data:image/gif;base64,R0lGODdhAgACALMAAAAAAP///wAAAAAAAP8AAAAAAAAAAAAAAAAA/wAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAAAgACAAAEAxBJFAA7', x: 0, y: 0 },
{ src: 'data:image/gif;base64,R0lGODdhAgACALMAAAAAAP///wAAAAAAAP8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACwAAAAAAgACAAAEA5BIEgA7', x: 20, y: 20 },
];
var canvas = document.createElement('canvas');
var destination = document.getElementById('canvas');
Promise.all(images.map(imageObj => add2canvas(canvas, imageObj)))
.then(() => destination.append(canvas));
function add2canvas(canvas, imageObj) {
return new Promise( (resolve, reject) => {
if (!imageObj || typeof imageObj != 'object') return reject();
var image = new Image();
image.onload = function () {
canvas.getContext('2d')
.drawImage(this, imageObj.x || 0, imageObj.y || 0);
resolve();
};
image.src = imageObj.src;
});
}
更多的铃声/口哨......用于生成复合png:
function mergeImageURIs(images) {
return new Promise( (resolve, reject) => {
var canvas = document.createElement('canvas');
canvas.width = 1000; // desired width of merged images
canvas.height = 1000; // desired height of merged images
Promise.all(images.map(imageObj => add2canvas(canvas, imageObj))).then(() => resolve(canvas.toDataURL('image/png'), reject));
});
}
function add2canvas(canvas, imageObj) {
return new Promise( (resolve, reject) => {
if (!imageObj || typeof imageObj != 'object') return reject();
var x = imageObj.x && canvas.width ? (imageObj.x >=0 ? imageObj.x : canvas.width + imageObj.x) : 0;
var y = imageObj.y && canvas.height ? (imageObj.y >=0 ? imageObj.y : canvas.height + imageObj.y) : 0;
var image = new Image();
image.onload = function () {
canvas.getContext('2d').drawImage(this, x, y);
resolve();
};
image.src = imageObj.src;
});
}