Hello i have problem i try to drawing image on the canvas with drawImage
function 50px x 50px on the 50px x 50px canvas, but i get smaller than i need.
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>
Don't set a canvas's width and height through CSS. This will stretch / compress the actual canvas, scaling the contents.
Use those old HTML width
and height
attributes instead:
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>
These attributes actually change the canvas's context's width and height, resulting in a image that's exactly the size you expect it to be.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.