【问题标题】:canvas background image is getting stretched画布背景图像被拉伸
【发布时间】:2015-11-19 18:02:27
【问题描述】:

我想在我的画布上放这张图片,但它被拉伸了,不能正确地装在盒子里。我错过了什么?

这是我的代码:

var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d");


var img = new Image();
img.src = "my image url";

img.onload = function(){
    ctx.drawImage(img,0,0);   
}

请查看此图片:http://i.stack.imgur.com/RMZM2.png

我想要的是我的徽标适合画布框。

这是我的整个徽标:http://i.stack.imgur.com/4jFjM.png

【问题讨论】:

标签: javascript html image canvas background


【解决方案1】:

如果你想让你的图像适合画布 -

ctx.drawImage(img,0,0,imgWidth,imgHeight,x,y, canvas.width, canvas.height);

其中 x 和 y 是您要显示徽标的左上角位置。 imgWidth 和 imgHeight 分别是您的徽标的宽度和高度。

参考这张图片。 http://www.html5canvastutorials.com/tutorials/html5-canvas-image-crop/

【讨论】:

  • 试过这个:ctx.drawImage(img,0,0,489,200,0,0, canvas.width, canvas.height);
  • 但它即将出现空白
  • 我实际上得到了它的工作,只是面临一个小问题。我用过这个:ctx.drawImage(img,0,0,canvas.width,canvas.height);但我的徽标图像仅适用于任何屏幕尺寸的 300x150。你能帮我看看为什么会这样吗?
  • user3657517 上下文中只有两个函数。 ctx.drawImage(img,x,y) 和 ctx.drawImage(img, sx, sy, sw,sy, dx,dy,dw,dh);其中 s 是源,d 是目标
  • 改为使用 - ctx.drawImage(img,0,0,imgwidth,imgheight, 0,0,canvas.width,canvas.height);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-02-23
  • 2011-11-12
  • 2017-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-19
相关资源
最近更新 更多