Html 自动将画布缩放到绘制的图像
我正在使用以下javascript将图像绘制到画布上Html 自动将画布缩放到绘制的图像,html,canvas,size,scale,drawimage,Html,Canvas,Size,Scale,Drawimage,我正在使用以下javascript将图像绘制到画布上 var canvas = document.getElementById('canvasId'); var ctx = canvas.getContext('2d'); var img = document.createElement('IMG'); img.onload = function () { ctx.drawImage(img, 0, 0,imgWidth,imgHeight); } img.src = "images
var canvas = document.getElementById('canvasId');
var ctx = canvas.getContext('2d');
var img = document.createElement('IMG');
img.onload = function () {
ctx.drawImage(img, 0, 0,imgWidth,imgHeight);
}
img.src = "images/testimg.jpg";
当我这样做时,我只看到原始图像的一部分。任何人都可以解释如何在画布上绘制整个原始图像,最好不指定原始照片的尺寸。将画布的高度和宽度设置为图像的高度和宽度
var canvas = document.getElementById('canvasId');
var ctx = canvas.getContext('2d');
var img = document.createElement('IMG');
canvas.height = ImgHeight;
canvas.width = ImgWidth;
img.onload = function () {
ctx.drawImage(img, 0, 0,imgWidth,imgHeight);
}
img.src = "images/testimg.jpg";
这里有一个@Ctrl-Alt Design答案的替代选项,它调整画布的大小以适合图像
var canvas = document.getElementById('canvasId');
var ctx = canvas.getContext('2d');
var img = document.createElement('IMG');
canvas.height = ImgHeight;
canvas.width = ImgWidth;
img.onload = function () {
ctx.drawImage(img, 0, 0,imgWidth,imgHeight);
}
img.src = "images/testimg.jpg";
此示例缩放图像以适合画布,同时保持图像的纵横比:
var img=new Image();
img.onload=start;
img.src="images/testimg.jpg";
function start(){
// calculate the scaling factor necessary
// to fit the image in the exsiting canvas size
// while maintaining the image's aspect ratio
var scaleFactor=Math.min((canvas.width/img.width),(canvas.height/img.height));
ctx.drawImage(img,0,0,img.width*scaleFactor,img.height*scaleFactor);
}