简体   繁体   English

如何在不损失分辨率的情况下使 Canvas HTML 图片更大?

[英]How do I make a Canvas HTML picture bigger without losing resolution?

My canvas size is 300x150.我的 canvas 尺寸为 300x150。 I don't want to set the measurements any bigger than this because I'd like it fit on mobile phones as well.我不想设置比这更大的测量值,因为我希望它也适合手机。 But i'd like it to scale up on bigger phones, ipads and laptops without losing resolution.但我希望它能够在更大的手机、ipad 和笔记本电脑上扩展而不损失分辨率。 The resolution on my canvas pictures have generally been bad and when it scales up it typically gets even worse.我的 canvas 图片的分辨率通常很差,当它放大时通常会变得更糟。 Not sure how to solve this problem.不知道如何解决这个问题。 Thanks.谢谢。 https://jsfiddle.net/uwakcgv0/ https://jsfiddle.net/uwakcgv0/

Here's the HTML:这是 HTML:

<canvas width="300" height="150" id="myCanvas"></canvas>

Here's the Javascript:这是 Javascript:

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, 300, 150);
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(20, 130);
ctx.lineTo(130, 130);
ctx.stroke();
ctx.fillText("y",18,15);
ctx.fillText("x",135,132);

Increase the canvas size by any factor and then scale the canvas by the same factor (using ctx.scale() ) to get the desired result.将 canvas 的大小增加任意因子,然后将 canvas 缩放相同的因子(使用ctx.scale() )以获得所需的结果。

 const SCALING_FACTOR = 2; var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d"); ctx.canvas.width = SCALING_FACTOR * canvas.width; ctx.canvas.height = SCALING_FACTOR * canvas.height; ctx.scale(SCALING_FACTOR, SCALING_FACTOR); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.beginPath(); ctx.moveTo(20, 20); ctx.lineTo(20, 130); ctx.lineTo(130, 130); ctx.stroke(); ctx.fillText("y", 18, 15); ctx.fillText("x", 135, 132);
 <canvas width="300" height="150" id="myCanvas"></canvas>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM