2013-05-19 84 views
0

當我修改HTML5畫布大小並繪製下一個文本時,文本的縱橫比出現偏斜。我不期望這種行爲。我究竟做錯了什麼?當畫布大小被修改時html5畫布行爲

<!DOCTYPE HTML> 
<html> 
    <script src="jquery-ui/js/jquery-1.9.1.js"></script>  
    <style> canvas{border:1px solid green} </style> 

    <body> 
    <canvas id="myCanvas" width="300" height="200"></canvas>  

    <script>  
    var canvas = document.getElementById('myCanvas'); 
    var context = canvas.getContext('2d'); 
    var height=200; 

    var myVar=setInterval(function(){repeat()},1000); 

    function repeat(){  
     $('#myCanvas').css("height",height+=50); 
     $('#myCanvas').css("width",300); 
     // var canvas = document.getElementById('myCanvas'); 
     // var context = canvas.getContext('2d'); 
     context.font = 'italic 40pt Calibri'; 
     context.fillText("Super test", 40, 100);   
    } 
    </script> 

enter image description here

+2

http://stackoverflow.com/questions/2588181/canvas-is-stretched-when-using-css-但正常-與寬度高度特性 – Andreas

回答

0

使用canvas.setAttribute('height', h);代替$('#myCanvas').css("height",h); ...

<!DOCTYPE HTML> 
<html> 
    <script src="jquery-ui/js/jquery-1.9.1.js"></script>  
    <style> canvas{border:1px solid green} </style> 

    <body> 
    <canvas id="myCanvas" width="300" height="200"></canvas>  

    <script>  
    var canvas = document.getElementById('myCanvas'); 
    var context = canvas.getContext('2d'); 
    var height=200; 

    var myVar=setInterval(function(){repeat()},1000); 

    function repeat(){  
     canvas.setAttribute('height', height+=50); 

     context.font = 'italic 40pt Calibri'; 
     context.fillText("Super test", 40, 100);   
    } 
    </script>