答案 0 :(得分:1)
你可以试试这个
//assuming cvs is your canvas reference
var ctx = cvs.getContext('2d');
cvs.width = yourImage.width;
cvs.height= yourImage.height;
ctx.lineWidth = x; // This is your border thickness
ctx.strokeStyle = '#000000';
ctx.rect(0,0,cvs.width,cvs.height);
ctx.stroke();
ctx.drawImage(yourImage,x,x,cvs.width-2*x,cvs.height-2*x);
为了适应边框,您的图像尺寸已经缩小了一些。然而,高度和宽度会有一些损失(边界宽度的2倍)。
如果要在添加边框后保留原始图像的纵横比,可以将最后一行更改为
ctx.drawImage(yourImage,x,x,cvs.width*(1- (2*x/cvs.width)),cvs.height*(1- (2*x/cvs.height)));
答案 1 :(得分:1)
如果要添加到图像,请将其转换为比原始图像大n个像素的画布并绘制边框。
该函数创建一个带边框的新图像amount
是边框宽度(以像素为单位),style
是您想要边框的颜色/样式。并且image
是原始图像。返回带边框的新图像
function borderImage(image,amount,style){
var paddedImage = document.createElement("canvas"); // create a new image
amount = Math.round(amount); // ensure that the amount is a int value
paddedImage.width = image.width + amount * 2; // set the size
paddedImage.height = image.height + amount * 2;
// get a context so you can draw on it
var ctx = paddedImage.getContext("2d");
ctx.strokeStyle = style; // set the colour;
ctx.lineWidth = amount;
// draw the border
ctx.strokeRect(amount / 2 , amount / 2, image.width + amount, image.height + amount);
// draw the image on top
ctx.drawImage(image, amount, amount);
return paddedImage ; // return the new image
}
使用
var image = new Image();
image.src = "http://i.stack.imgur.com/u2n6E.png";
image.onload = function(){
image = borderImage(this,8,"black");
document.body.appendChild(image);
}
function borderImage(image,amount,style){
var paddedImage = document.createElement("canvas"); // create a new image
amount = Math.round(amount); // ensure that the amount is a int value
paddedImage.width = image.width + amount * 2; // set the size
paddedImage.height = image.height + amount * 2;
// get a context so you can draw on it
var ctx = paddedImage.getContext("2d");
ctx.strokeStyle = style; // set the colour;
ctx.lineWidth = amount;
// draw the border
ctx.strokeRect(amount / 2 , amount / 2, image.width + amount, image.height + amount);
// draw the image on top
ctx.drawImage(image, amount, amount);
return paddedImage ; // return the new image
}
var image = new Image();
image.src = "http://i.stack.imgur.com/u2n6E.png";
image.onload = function(){
image = borderImage(this,8,"black");
document.body.appendChild(image);
}