newbStudent
newbStudent

Reputation: 35

Blurry svg in canvas

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>

Upvotes: 3

Views: 4771

Answers (2)

Felix Fong
Felix Fong

Reputation: 985

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/

Upvotes: -2

B&#225;lint
B&#225;lint

Reputation: 4039

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.

Upvotes: 4

Related Questions