简体   繁体   English

javascript:canvas.drawImage如何工作

[英]javascript: how does canvas.drawImage work

I'm trying to draw an image onto a canvas, like this: 我正在尝试将图像绘制到画布上,如下所示:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("scream");
ctx.drawImage(img,0,0,100,100,0,0,200,200);

The canvas is 200px by 200px and the image is much bigger (but styled at 200px by 200px too) 画布为200px x 200px,图像更大(但样式也设置为200px x 200px)

As you can see in the jsfiddle the canvas doesn't show the image (I was expecting a part of the image). 正如您在jsfiddle中看到的那样 ,画布不显示图像(我期待图像的一部分)。 My understanding of drawImage (as is described here ) goes like this: 我的drawImage(如描述的理解这里 )是这样的:

  • "0,0,100,100" defines a rectangle on the image which is the part that is drawn onto the canvas. “ 0,0,100,100”在图像上定义一个矩形,该矩形是绘制到画布上的部分。 0,0 defines the top/left corner and 100,100 are the widths of the sides. 0,0定义了上/左角,而100,100是边的宽度。
  • This rectangle is drawn onto the canvas inside the rectangle defined by 0,0,200,200 该矩形被绘制到由0,0,200,200定义的矩形内的画布上

Any suggestions what goes wrong here ? 有什么建议在这里出什么问题吗?

You image is actually 585 x 585 so what you are doing is to clip a corner from it (which is blank) and draw it onto canvas which of course won't show anything. 您的图像实际上是585 x 585,因此您要做的是从图像上修剪一个角(空白)并将其绘制到画布上,这当然不会显示任何内容。

Scaling the image with CSS doesn't actually change its size. 使用CSS缩放图像实际上并不会改变其大小。 It only scales it for display. 仅缩放显示。

So what you need to do is to use the original size of the image as basis. 因此,您需要做的是使用图像的原始大小作为基础。 If you simply want to scale it down to fit in canvas you can do: 如果您只是想将其缩小以适合画布,则可以执行以下操作:

ctx.drawImage(img, 0, 0, 200, 200);

The same goes for canvas. 画布也是如此。 Don't scale canvas using CSS but set the width and height properties/attributes or else the canvas will default to 300x150 (which is then scaled by your css): 不要使用CSS缩放画布,而是设置width和height属性/属性,否则画布将默认设置为300x150(然后由CSS缩放):

<canvas width=200 height=200 ...>

Modified fiddle 改良的小提琴

Set the width and height on the canvas and draw the image at the same dimensions. 在画布上设置宽度和高度,并以相同的尺寸绘制图像。 Updated your fiddle - http://jsfiddle.net/FQhGg/2/ 更新了您的小提琴-http: //jsfiddle.net/FQhGg/2/

var c=document.getElementById("myCanvas"),
    ctx=c.getContext("2d"),
    img=document.getElementById("scream"),
    width = img.width,
    height = img.height;

c.width = width;
c.height = height;
ctx.drawImage(img,0,0,width,height);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM