HTML5画布的大小和分辨率之间有什么关系 [英] What is the relation between the size and resolution of HTML5 canvas
问题描述
有没有办法可以创建大尺寸但低分辨率的画布。我用语法< canvas id =mycanvaswidth =700height =1000>< / canvas>
声明画布。我在7英寸平板电脑上运行上面的代码,画布跨越画布的一半屏幕。有没有办法我可以创建一个画面,再次覆盖屏幕的一半但分辨率较低(图像质量较低)。
实际上我在画布上绘制一些东西,然后使用canvas.toDataURL()将其保存为图像。我不需要获得高质量的图像,但我想降低生成图像的大小。
Is there a way by which I can create a canvas of large size but low resolution. I'm declaring the canvas with the syntax <canvas id="mycanvas" width="700" height="1000"></canvas>
. I'm running the above code on a 7 inch tablet and the canvas spans half of the screen of the canvas. Is there a way by which I can create a canvas which again covers half of the screen but has a lower resolution (lower quality of image).
Actually I draw something on the canvas and then save it as image by using canvas.toDataURL(). I don't need to get good quality image, but I want to lower the size of the image generated.
如果这是一个愚蠢的问题,请原谅我
Forgive me if it's a silly question
推荐答案
首先,像这样缩放你的画布元素(在javascript中):
First, scale your canvas element like this (in javascript):
canvas.width=canvas1.width*scaleFactor;
canvas.height=canvas1.height*scaleFactor;
警告:如果使用CSS缩放画布,则可能会扭曲画布上绘制的图像
Warning: If you scale the canvas using CSS, you will likely distort images drawn on the canvas
然后你可以使用一些添加的参数来缩放图像 context.drawImage
Then you can scale your image using some added arguments to 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>
这篇关于HTML5画布的大小和分辨率之间有什么关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!