问题
Why SVG doesn't scale correctly in canvas (it is all pixelated and blurry) ? What am I doing wrong ?
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>
回答1:
Your problem isn't with the SVG, it's with the canvas.
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.
回答2:
I think you can put the SVG inside a div
and then blur the div,so it will get the same effect
https://jsfiddle.net/moongod101/q3qh78xd/
来源:https://stackoverflow.com/questions/38061836/blurry-svg-in-canvas