合并两个 dataURI 以创建单个图像 [英] Merge two dataURIs to create a single image
问题描述
我想生成由标签和图标组成的图像.标签部分会变化很大(50-100),而大约有 10 个图标.我想通过将最终图像分成两部分(标签图像和图标图像)以模块化方式制作最终图像.我将构建一个服务,该服务返回标签的 dataURI,而图标 dataURI 将嵌入到页面中.然后我想组合这两个不同的 dataURI 来创建一个表示组合图像的单个 dataURI.
I want to generate images consisting of a label and an icon. The label part is going to vary a lot (50-100) while there are about 10 icons. I would like to make the final images in a modular way by splitting the final image in two parts, a label image and an icon image. I will build a service that returns dataURI for the labels while the icon dataURIs will be embedded in the page. Then I would like to combine these two different dataURIs to create a single dataURI representing a combined image.
如何在客户端执行此操作?
How can I do this on the client side?
推荐答案
您可以使用数据 uri 创建图像,然后使用 canvas
绘制包含它们的新图像.这是一个简单的例子:
You can create images using your data uris and then draw a new image that includes them using canvas
. Here's a simple example:
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
命令组合后,您可以使用画布创建新图像,例如:
Once you have the images loaded from the data URI and combined using the drawImage
commands of the canvas context you can use the canvas to create a new image like:
var combined = new Image;
combined.src = canvas.toDataURL('data/gif');
不幸的是,这在 IE8 中不起作用.
Unfortunately this won't work in IE8.
这篇关于合并两个 dataURI 以创建单个图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!