【发布时间】:2016-05-03 10:44:02
【问题描述】:
我正在使用 HTML5 画布和 jQuery/JS 开发图像生成器。我想要完成的是以下内容。
用户可以上传 2 张或最多 3 张图片(类型应为 png 或 jpg)到画布。生成的图像应始终为 1080x1920。如果 hart 只上传 2 张图片,则图片为 1080x960。如果上传 3 张图片,则每张图片的尺寸应为 1080x640。
上传2或3张图片后,用户可以点击下载按钮获取合并后的图片,格式为1080x1920px。
它应该使用 html canvas 来完成。
我想出了这个:
HTML:
<canvas id="canvas">
Sorry, canvas not supported
</canvas><!-- /canvas.offers -->
<input id="fileInput" type="file" />
<a href="#" class="generate">Generate</a>
jQuery:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
canvas.height = 400;
canvas.width = 800;
var img1 = loadImage('http://www.shsu.edu/dotAsset/0e829093-971c-4037-9c1b-864a7be1dbe8.png', main);
var img2 = loadImage('https://upload.wikimedia.org/wikipedia/commons/thumb/c/c5/Ikea_logo.svg/266px-Ikea_logo.svg.png', main);
var minImages = 2;
var imagesLoaded = 0;
function main() {
imagesLoaded += 1;
if(imagesLoaded >= minImages) {
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.save();
ctx.drawImage(img1, 0, 0);
// ctx.translate(canvas.height/2,canvas.width/2); // move to the center of the canvas
// ctx.rotate(270*Math.PI/180); // rotate the canvas to the specified degrees
// ctx.drawImage(img2,0,canvas.height/2);
ctx.translate(-canvas.height/2,canvas.width/2); // move to the center of the canvas
ctx.rotate(90*Math.PI/180); // rotate the canvas to the specified degrees
ctx.drawImage(img2,-img2.width/2,-img2.width/2);
ctx.restore(); // restore the unrotated context
}
}
function loadImage(src, onload) {
var img = new Image();
img.onload = onload;
img.src = src;
console.log(img);
return img;
}
上面的代码将创建画布并将两个图像(现在在 JS 中硬编码)放置到创建的画布上。它将旋转 90 度,但不会定位到右上角。第二张图片也应该位于第一张图片旁边。
如何并排旋转和定位每张图片?
【问题讨论】:
标签: javascript jquery html canvas