1

現在、キャンバス要素を含むプロジェクトに取り組んでおり、キャンバスのサイズを変更すると問題が発生しました。幅と高さを 2 で割ってキャンバスの中央に画像を描画しようとしていますが、キャンバスのサイズを変更するたびに HTML のみが変更されるため、画像を再描画しようとすると、まだ半分に描画されます古いキャンバスの幅と高さ。これがDOMの問題なのかどうかはわかりませんが、助けていただければ幸いです。Safari、FF、および Chrome でテストしました

編集:コード

<body>
<div id="holder">
<div id="dropdown">
  <div id="ddcontents" style="display: none;">
    <button onclick="fade()">Options</button>
    <button onclick="getSize()">Canvas Size</button>
    <button onclick="redraw()" disabled="true">Redraw</button>
  </div>
</div>
<canvas id="c" height="480" width="640">Your browser does not support HTML5.</canvas>
<div id="options" style="display: none">
 <div id="optcontent" style="display: none">
    <center><h1>Options</h1></center>       
    <div id="sound">
        <div>Volume:
            <form oninput="volumenumber.value = parseInt(volume.value)">
                <input type="range" name="volume" min="0" max="100" value="80" disabled="true">
                <input type="hidden" name="hello" value="%">
                <output name="volumenumber" for="volume">80</output>
            </form>
            Resolution:
            <select id="resolution">
                <option value="480p">480x640</option>
                <option value="720p">720x1280</option>
            </select>
        </div>
    </div>
    <div id="closeoptions">
        <button onclick="apply()">Apply</button>
        </div>
    </div>
</div>

</div>


<script src="options.js"></script>
</body>
</html>

そしてJSの場合:

var c = document.getElementById('c');
var ctx=c.getContext("2d");
var img=new Image();
var w = this.c.clientWidth; // stores the width for later use
var h = this.c.clientHeight;
this.c.width = w;
this.c.height = h;
var cwidth = c.width;
var cheight = c.height;

img.onload = function(){
ctx.drawImage(img,w/2 - 14,h/2 - 19);
};
img.src="image_preview.png";


function apply()
{
var reso = document.getElementById("resolution");
var resol = reso.options[reso.selectedIndex].value;
//alert(resol)
if (resol == "720p")
 {
    //alert("You changed to 720p");
    h = 720;
    w = 1280;
    cheight = 720;
    cwidth = 1280;
 }
else if (resol == "480p")
 {
    //alert("You changed to 480p");
    h = 480;
    w = 640;
    cheight = 480;
    cheight = 640;
 }
getSize();
redraw();
}

function redraw()
{
ctx.drawImage(img,w/2 - 14,h/2 - 19);
img.src="image_preview.png";
}

function getSize()
{
alert(h + "x" + w);
}
4

1 に答える 1

0

キャンバスを使用する場合、その内部構造がレンダリング html ゾーンと同じサイズであることを確認する必要があります。

出来るよ :

this.canvas.width = this.canvas.clientWidth;
this.canvas.height = this.canvas.clientHeight;

通常、レンダリング計算のためにこれらの寸法も保存します。

var w = this.canvas.clientWidth; // stores the width for later use
var h = this.canvas.clientHeight;
this.canvas.width = w;
this.canvas.height = h;

編集:要素のサイズを変更するには、前のコードの前に次のようなことを行います:

$('#mycanvas').width(newWidthInPx);
于 2012-08-17T18:11:18.330 に答える