HTML5 canvas:图片调整大小 [英] HTML5 canvas: image resizing

查看:2810
本文介绍了HTML5 canvas:图片调整大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在一个画布上放置一个图像,而不调整它的大小。我想drawImage(img,x,y)会做的伎俩,但它拉伸图像填充画布。
也提供drawImage(img,x,y,width,height)与我的图像的尺寸似乎不工作。



这里是我的代码:

 < canvas id =storystyle =position:relative; width:800px; height:600px;> < / canvas> 

< script type =text / javascript>

window.onload = function(){
var canvas = document.getElementById(story);
var context = canvas.getContext(2d);
var img = document.getElementById(img1);
var width = parseInt(img.width);
var height = parseInt(img.height);
context.drawImage(img,0,0,width,height);
}

< / script>
< img id =img1alt =src =http:// link to image/>

提前感谢!



<我添加了parseInt以确保drawImage获取有效的值。

解决方案

不要使用CSS来调整画布大小。这将创建一个默认大小的画布并拉伸它。直接在其上设置画布尺寸,您将获得1到1像素的绘图空间。

 < canvas id = storywidth =800height =600style =position:relative;>< / canvas> 


I'm trying to place an image on a canvas without resizing it. I thought drawImage(img, x, y) would do the trick, but it stretches the image to fill the canvas. Also supplying drawImage(img, x, y, width, height) with the dimensions of my image doesn't seem to work.

Here's my code:

<canvas id="story" style="position:relative; width:800px; height:600px;"></canvas>

<script type="text/javascript">

window.onload = function() {
  var canvas = document.getElementById("story");
  var context = canvas.getContext("2d");
  var img = document.getElementById("img1");
  var width = parseInt(img.width);
  var height = parseInt(img.height);
  context.drawImage(img, 0, 0, width, height);
}

</script>
<img id="img1" alt="" src="http://link to image"/>

Thanks in advance!

PS: I added the parseInt's to make sure that drawImage gets valid values.

解决方案

Don't use CSS to size your canvas. That creates a default sized canvas and stretches it. Set the canvas dimensions directly on it and you'll get a 1 to 1 pixel drawing space.

<canvas id="story" width="800" height="600" style="position:relative;"></canvas>

这篇关于HTML5 canvas:图片调整大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆