html5 canvas collage,javascript - HTML5 Canvas - Image collage with borders - Stack Overflow

My idea is drawing the rectangle border first and then draw the images.

Another thing is the way that you are drawing the rectangles. If you wanna draw rectangles this is the code snippet:

ctx.beginPath();

ctx.rect(width / 2 * (-1), height / 2 * (-1), width, height);

ctx.lineWidth = 5;

ctx.strokeStyle = 'white';

ctx.stroke();

Another thing too, is the way that you turn back to the original position. There's a more simple way with the use of ctx.save() and ctx.restore(). This is the way that canvas propose you to turn back when you are doing transformations.

So here is my solution I hope that you enjoy it. Thanks Sergio.

function loadImages(sources, callback) {

var images = {};

var loadedImages = 0;

var numImages = 0;

// get num of sources

for(var src in sources) {

numImages++;

}

for(var src in sources) {

images[src] = new Image();

images[src].onload = function() {

if(++loadedImages >= numImages) {

callback(images);

}

};

images[src].src = sources[src];

}

}

var canvas = document.getElementById('myCanvas');

var context = canvas.getContext('2d');

var sources = {

bg: 'bg2.jpg',

a: 'a.jpg',

b: 'b.jpg',

c: 'c.jpg',

d: 'd.jpg',

e: 'e.jpg',

f: 'f.jpg'

};

function drawRectanlesBorders(img,x,y,width,height,deg){

var c=document.getElementById("myCanvas");

var ctx=c.getContext("2d");

var rad = deg * Math.PI / 180;

ctx.save();

ctx.translate(x + width / 2, y + height / 2);

ctx.rotate(rad);

ctx.beginPath();

ctx.rect(width / 2 * (-1), height / 2 * (-1), width, height);

ctx.lineWidth = 5;

ctx.strokeStyle = 'white';

ctx.stroke();

ctx.restore();

}

function drawImageRot(img,x,y,width,height,deg){

var c=document.getElementById("myCanvas");

var ctx=c.getContext("2d");

var rad = deg * Math.PI / 180;

ctx.save();

ctx.translate(x + width / 2, y + height / 2);

ctx.rotate(rad);

ctx.drawImage(img,width / 2 * (-1),height / 2 * (-1),width,height);

ctx.restore();

}

loadImages(sources, function(images) {

//draw background image

drawImageRot(images.bg, 0, 0, 600, 600,0);

//draw borders

drawRectanlesBorders(images.b, 380, 55,277, 184,-20);

drawRectanlesBorders(images.a,-20,-20, 300, 224,-30);

drawRectanlesBorders(images.e, 130, 150,350, 274,0);

drawRectanlesBorders(images.d, 320, 430,277, 184,20);

drawRectanlesBorders(images.f, 0, 380, 240,160,-10);

//draw images

drawImageRot(images.b, 380, 55,277, 184,-20);

drawImageRot(images.a,-20,-20, 300, 224,-30);

drawImageRot(images.e, 130, 150,350, 274,0);

drawImageRot(images.d, 320, 430,277, 184,20);

drawImageRot(images.f, 0, 380, 240,160,-10);

});

You should decide the order to paint the images too see what you really wanna see.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值