首先,擴大你這樣的canvas元素(在JavaScript):
canvas.width=canvas1.width*scaleFactor;
canvas.height=canvas1.height*scaleFactor;
警告:如果您在使用CSS擴展畫布,你很可能會扭曲圖像畫在畫布
然後你可以使用一些額外的參數擴展您的圖像上context.drawImage
var scaleFactor=0.50;
ctx2.drawImage(img, 0,0,img.width,img.height,
0,0,img.width*scaleFactor,img.height*scaleFactor);
![enter image description here](https://i.stack.imgur.com/jhdzB.png)
這裏是代碼和一個小提琴:http://jsfiddle.net/m1erickson/6m8kg/
<!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; padding:15px;}
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas1=document.getElementById("canvas1");
var ctx1=canvas1.getContext("2d");
var canvas2=document.getElementById("canvas2");
var ctx2=canvas2.getContext("2d");
var scaleFactor=0.50;
var img=document.createElement("img");
img.onload=function(){
// draw the image full-size on the larger canvas
ctx1.drawImage(img,0,0);
// resize the canvas
// Don't use css to resize, it will distort your image
// The scaling is done with the added drawImage arguements
canvas2.width=canvas1.width*scaleFactor;
canvas2.height=canvas1.height*scaleFactor;
// draw a scaled-down image into the second canvas
ctx2.drawImage(img, 0,0,img.width,img.height,
0,0,img.width*scaleFactor,img.height*scaleFactor);
}
img.src="faces.png";
}); // end $(function(){});
</script>
</head>
<body>
<p>Top canvas is full-sized</p>
<canvas id="canvas1" width=400 height=242></canvas><br>
<p>Bottom canvas is scaled down</p>
<canvas id="canvas2" width=300 height=300></canvas>
</body>
</html>
HTML屬性('寬度= 「700」 HEIGHT = 「1000」')描述了畫布的*邏輯*尺寸,即,您可以在理論上將多少個像素放置在畫布上並單獨地放置。 CSS屬性('canvas#mycanvas {width:700px; height:1000px;}')描述了所述畫布的可視大小。瀏覽器將拉伸畫布的邏輯像素以適應可視區域。 – DCoder