11

Raphael を使用してオブジェクトを描画し、canvg を使用して HTML キャンバス要素に転送し、toDataURL を使用して PNG として保存できるようにしています。しかし、canvg を使用すると、結果の画像がぼやけます。たとえば、以下のコードはこれを生成します (上が raphael、下が canvg):

ここに画像の説明を入力

<html>
    <head>
        <script src="lib/raphael-min.js"></script>
        <script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/rgbcolor.js"></script> 
        <script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/StackBlur.js"></script>
        <script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/canvg.js"></script> 
        <script src="lib/raphael.export.js"></script>
    </head>
    <body>

    <div id="raph_canvas"></div><br> 
    <canvas id="html_canvas" width="50px" height="50px"></canvas>

    <script language="JavaScript">
    var test=Raphael("raph_canvas",50,50);
    var rect=test.rect(0,0,50,50);
    rect.attr({fill: '#fff000', 'fill-opacity':1, 'stroke-width':1})

    window.onload = function() {
        var canvas_svg = test.toSVG();
        canvg('html_canvas',canvas_svg);
        var canvas_html = document.getElementById("html_canvas");
    }

    </script>
    </body>
</html>

ぼやけは、toDataURL によって作成された png でも明らかです。ここで何が起こっているのか分かりますか?サイズ直しとは関係ないと思います。ignoreDimensions: True などを設定してみました。

別のデータポイント。raphael を使用してテキストを出力してから canvg を使用すると、ぼやけるだけでなく、間違ったフォントになります!

ここに画像の説明を入力

そして、ここに test.rect(0.5,0.5,50,50) が提案されています。まだぼやけています:

ここに画像の説明を入力

4

2 に答える 2

16

それでしばらく時間がかかりましたが、それから私は気づきました。すべてのサンプル画像は、コードが主張するサイズの 2 倍です。したがって、おそらくある種の HDPI デバイス (Retina MacBook Pro など...) を使用している可能性があります。SVG は解像度に依存しないため優れていますが、キャンバスはそうではありません。表示されている問題は、キャンバスのレンダリング方法に関係しています。これを修正するには、画面の解像度で描画が行われるようにキャンバスを準備する必要があります。

http://jsbin.com/liquxiyi/3/edit?html,js,出力

この jsbin の例は、どの画面でも見栄えがするはずです。

トリック:

var cv = document.getElementById('box');
var ctx = cv.getContext("2d");

// SVG is resolution independent. Canvas is not. We need to make our canvas 
// High Resolution.

// lets get the resolution of our device.
var pixelRatio = window.devicePixelRatio || 1;

// lets scale the canvas and change its CSS width/height to make it high res.
cv.style.width = cv.width +'px';
cv.style.height = cv.height +'px';
cv.width *= pixelRatio;
cv.height *= pixelRatio;

// Now that its high res we need to compensate so our images can be drawn as 
//normal, by scaling everything up by the pixelRatio.
ctx.setTransform(pixelRatio,0,0,pixelRatio,0,0);


// lets draw a box
// or in your case some parsed SVG
ctx.strokeRect(20.5,20.5,80,80);

// lets convert that into a dataURL
var ur = cv.toDataURL();

// result should look exactly like the canvas when using PNG (default)
var result = document.getElementById('result');
result.src=ur;

// we need our image to match the resolution of the canvas
result.style.width = cv.style.width;
result.style.height = cv.style.height;

これはあなたが抱えている問題を説明し、うまくいけばそれを修正するための良い方向にあなたを向けるはずです.

于 2014-06-25T03:32:08.403 に答える