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 回答