javascript drawImage 并调整为 Canvas
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15192343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
drawImage and resize to Canvas
提问by Philip Kirkbride
I have an image which is 1836 x 3264 I want to drawImage()
to canvas and resize to 739 x 1162.
我有一个 1836 x 3264 的图像,我想drawImage()
画布并将其调整为 739 x 1162。
After reading the documentation I thought this could be accomplished with the following:
阅读文档后,我认为这可以通过以下方式完成:
ctx.drawImage(image, 0, 0, 739, 1162);
I have also tried:
我也试过:
ctx.drawImage(image, 0, 0, 1836, 3264, 0, 0, 739, 1162);
Both show only a small part of the full image instead of shrinking it down.
两者都只显示完整图像的一小部分,而不是将其缩小。
How do I pass through the values to resize from 1836 x 3264 -> 739 x 1162 ?
如何传递值以从 1836 x 3264 -> 739 x 1162 调整大小?
回答by markE
What you have looks correct, so you might double-check for a typo somewhere.
您所拥有的看起来是正确的,因此您可能会在某处仔细检查是否有错别字。
[additional thought: Is your image really 1836x3264 and not 3264x1836.]
[额外的想法:你的图片真的是 1836x3264 而不是 3264x1836。]
Here is working code and a Fiddle: http://jsfiddle.net/m1erickson/MLGr4/
这是工作代码和小提琴:http: //jsfiddle.net/m1erickson/MLGr4/
<!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");
img=new Image();
img.onload=function(){
canvas.width=400;
canvas.height=300;
ctx.drawImage(img,0,0,img.width,img.height,0,0,400,300);
}
img.src="http://www.onestopwebmasters.com/wp-content/uploads/2011/06/eitai-bridge.jpg";
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=100 height=100></canvas>
</body>
</html>