使用 Javascript 合并图像 [英] Merge Image using Javascript

查看:21
本文介绍了使用 Javascript 合并图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用javascript合并图片?

Is it possible to merge pictures using javascript?

例如,如果您有 2 个大小相同的矩形 .jpg 或 .png 图像文件,是否可以将它们并排对齐并以新的 .jpg 或 .png 格式生成两者的合并副本图像文件?

For example, if you have 2 rectangle .jpg or .png images files of the same size, is it possible that you can align it side by side and produce a merged copy of the two in a new .jpg or .png image file?

推荐答案

您可以使用 JavaScript 将它们合并"到一个画布中,并将该画布转换为图像.

You can use JavaScript to 'merge' them into one canvas, and convert that canvas to image.

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var imageObj1 = new Image();
var imageObj2 = new Image();
imageObj1.src = "1.png"
imageObj1.onload = function() {
   ctx.drawImage(imageObj1, 0, 0, 328, 526);
   imageObj2.src = "2.png";
   imageObj2.onload = function() {
      ctx.drawImage(imageObj2, 15, 85, 300, 300);
      var img = c.toDataURL("image/png");
      document.write('<img src="' + img + '" width="328" height="526"/>');
   }
};

出于安全考虑,您的两张图片必须与您的 JavaScript 文件位于同一域(即 http://123.com/1.pnghttp://123.com/2.pnghttp://123.com/script.js) 否则函数 toDataURL() 将引发错误.

Due to security, your two images must be on the same domain with your JavaScript file (i.e http://123.com/1.png, http://123.com/2.png and http://123.com/script.js) otherwise the function toDataURL() will raise an error.

这篇关于使用 Javascript 合并图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆