有没有办法可以创建大尺寸但低分辨率的画布。我用语法<canvas id="mycanvas" width="700" height="1000"></canvas>
声明画布。我在7英寸平板电脑上运行上面的代码,画布跨越画布的一半屏幕。有没有办法我可以创建一个画面,再次覆盖屏幕的一半,但分辨率较低(图像质量较低)。
实际上我在画布上绘制了一些东西,然后使用canvas.toDataURL()将其保存为图像。我不需要获得高质量的图像,但我想降低生成图像的大小。
如果这是一个愚蠢的问题,请原谅我
答案 0 :(得分:2)
首先,像这样缩放你的画布元素(在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);
这是代码和小提琴: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>