画布中的模糊svg [英] Blurry svg in canvas
问题描述
为什么SVG在画布中无法正确缩放(像素化和模糊化)?我在做什么错了?
Why SVG doesn't scale correctly in canvas (it is all pixelated and blurry) ? What am I doing wrong ?
我想要的是无论画布大小如何,SVG图像均保持其宽高比,而且还不会使其变得模糊.
All I want is the SVG image to keep it's aspect ratio whatever the canvas size, and alose not have it becoming blurry.
var canvas = document.getElementById("screen"),
ctx = canvas.getContext("2d");
var img = new Image();
img.src = "http://imgh.us/perso.svg";
img.onload = function() {
ctx.drawImage(img, 0, 0);
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
}
#screen {
display: block;
width: 100%;
height: 100%;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<title>Game</title>
</head>
<body>
<canvas id="screen"></canvas>
<script type="text/javascript" src="js/game.js"></script>
</body>
</html>
推荐答案
您的问题不在于SVG,而在于画布.
Your problem isn't with the SVG, it's with the canvas.
画布的默认大小为300×150.首先要运行的是脚本,它创建画布上下文,其大小应为300×150.然后CSS出现,并将画布元素在每个方向上缩放为100%.上下文仍然是300×150.这使得每个像素占用1个以上的像素区域.您需要确保脚本在CSS之后运行,或者需要使用JavaScript来调整画布大小.
Canvases have a default size of 300 × 150. The first thing, wich runs is the script, it creates the canvas context, wich is 300 × 150. Then CSS comes, and scales the canvas element to 100% in each direction. The context is still 300 × 150. This makes every pixel take up more than 1 pixel area. You need to make sure your script runs after the CSS or you need to use javascript, to resize the canvas.
这篇关于画布中的模糊svg的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!