html - HTML5 Canvas 的大小和分辨率有什么关系

标签 html html5-canvas

有没有一种方法可以创建大尺寸但低分辨率的 Canvas 。我使用语法 <canvas id="mycanvas" width="700" height="1000"></canvas> 声明 Canvas .我在 7 英寸平板电脑上运行上面的代码, Canvas 横跨 Canvas 屏幕的一半。有没有一种方法可以创建一个再次覆盖屏幕一半但分辨率较低(图像质量较低)的 Canvas 。 实际上,我在 Canvas 上画了一些东西,然后使用 canvas.toDataURL() 将其保存为图像。我不需要获得高质量的图像,但我想减小生成的图像的大小。

如果这是一个愚蠢的问题,请原谅我

最佳答案

首先,像这样缩放 Canvas 元素(在 javascript 中):

    canvas.width=canvas1.width*scaleFactor;
    canvas.height=canvas1.height*scaleFactor;

警告:如果您使用 CSS 缩放 Canvas ,您可能会扭曲 Canvas 上绘制的图像

然后您可以使用一些添加到 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

这是代码和 fiddle :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 - HTML5 Canvas 的大小和分辨率有什么关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17260867/

相关文章:

javascript - 如何在我的 js 下拉/显示内容框的不同内容之间切换

javascript - 更新 firefox 55 后,内联图像 (img) 未通过 SVG 在 HTML CANVAS 中呈现

javascript - 将 Canvas 图像上传到 S3 服务器

javascript - 按键干扰 canv.onmousedown();

javascript - Fabric.JS 和 Fabric-Brush - 无法添加到下部 Canvas

html - 图像和 anchor ,如何将对齐应用于链接文本?

html - 我如何修改我的代码以与 !doctype html 兼容

html - 使用 ModelForms 在 Django 中上传文件

html - 字体选择器的字体属性在我的网站上不起作用

javascript - 在 Canvas 上绘制具有 2 个点的图像