[英]HTML5 canvas drawImage incorrect image size
您好我有問題我嘗試在畫布上使用drawImage
函數50px x 50px在50px x 50px畫布上繪制圖像,但我比我需要的要小。
var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var img = new Image(); img.onload = function() { $("canvas").css("width", 50); $("canvas").css("height", 50); ctx.drawImage(img, 0, 0, 50, 50); //bad here why not drawing 50x50px image on the canvas? } img.src = 'http://www.w3schools.com/tags/planets.gif';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <img src="http://www.w3schools.com/tags/planets.gif" width="100" height="100" style="position: absolute; top: 0px; left: 0px"> <canvas id="canvas" style="position: absolute; top: 0px; left: 120px; border: 1px solid #000"></canvas>
不要通過CSS設置畫布的寬度和高度。 這將拉伸/壓縮實際畫布,縮放內容。
請改用舊的HTML width
和height
屬性:
var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var img = new Image(); img.onload = function() { ctx.drawImage(img, 0, 0, 50, 50); } img.src = 'http://www.w3schools.com/tags/planets.gif';
<img src="http://www.w3schools.com/tags/planets.gif" width="100" height="100" style="position: absolute; top: 0px; left: 0px"> <canvas id="canvas" style="position: absolute; top: 0px; left: 120px; border: 1px solid #000" width="50" height="50"> </canvas>
這些屬性實際上會更改畫布的上下文的寬度和高度,從而產生與您期望的大小完全相同的圖像。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.