我在将图像绘制到尺寸合适的画布时遇到了问题。
这是我的简单代码:
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
$(canvas).css('width', '100px');
$(canvas).css('height', '75px');
context.drawImage(img, 0, 0, 100, 75);
我希望画布上绘制的图像宽度为100,高度为75。结果不是那么大,而是更小的尺寸
像这样:预计顶角的花朵会填满整个红色区域。 有谁知道原因?
答案 0 :(得分:3)
当您使用CSS重置画布大小时,您只需"拉伸"像素。
因此,要更改画布上的像素数,必须设置画布元素的宽度和宽度。高度。
示例代码和演示:http://jsfiddle.net/m1erickson/G74zt/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var img=new Image();
img.crossOrigin="anonymous";
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house-icon.png";
function start(){
var ratio=calculateProportionalAspectRatio(
img.width,img.height,canvas.width,canvas.height);
ctx.drawImage(img,0,0,img.width*ratio,img.height*ratio);
}
// Calculate the ratio that fills the canvas
// but doesn't stretch the image pixels
// (This may cause some pixels to be clipped)
function calculateProportionalAspectRatio(srcWidth, srcHeight, maxWidth, maxHeight) {
return(Math.min(maxWidth / srcWidth, maxHeight / srcHeight));
}
}); // end $(function(){});
</script>
</head>
<body>
<h4>Original Image</h4>
<img src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/house-icon.png">
<h4>Resize image proportionally to fill canvas</h4>
<canvas id="canvas" width=350 height=350></canvas>
</body>
</html>
答案 1 :(得分:1)
当javascript调整大小时,图像已经在画布上,因此图像继承了新的大小。 尝试将画布调整为一些任意起始值的一小部分,如下所示:
<img id="img" src="myimage.png">
<canvas id="canvas" height="750" width="1000">
<script>
var originalwidth=1000;
var originalheight=750;
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var img=document.getElementById('img');
$(canvas).css('width', originalwidth/10);
$(canvas).css('height', originalheight/10);
context.drawImage(img,0,0,originalwidth,originalheight);
</script>
这假设你不能在HTML中设置画布的初始大小,这是更好的选择。