我希望生成由标签和图标组成的图片。标签部分将会有很多变化(50-100),而图标只有大约10个。我想通过将最终的图片分成两个部分,一个标签图片和一个图标图片,以模块化的方式制作最终的图片。我将构建一个服务来返回标签数据URI,而图标数据URI将被嵌入到页面中。然后我想将这两种不同的数据URI组合起来创建一个单一的数据URI,代表一个组合图像。
如何在客户端上实现这个功能?
如何在客户端上实现这个功能?
您可以使用数据URI创建图像,然后使用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中无法正常运行。
使用包含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;
});
}