简体   繁体   English

使用JavaScript绘制到HTML5画布时调整.png图像的大小

[英]Resizing a .png image when drawing to HTML5 canvas using JavaScript

I am trying to draw a few .png images to the HTML5 canvas using JavaScript. 我正在尝试使用JavaScript在HTML5画布上绘制一些.png图像。 I currently have a function that will draw an image to the canvas, but the image is too large for the canvas, so only part of it displays. 我目前有一个将图像绘制到画布上的函数,但是该图像对于画布而言太大,因此仅显示一部分。

The function I currently have is: 我目前拥有的功能是:

function drawImage(x, y){
            var numberImage = new Image();
            numberImage.src = imageSource;
            context.drawImage(numberImage, x, y);

        }

and I call the function by using: 然后使用以下命令调用该函数:

var image1 = new Image();

image1.onLoad = function(){
                context.drawImage(image1, 50, 50);
                };
            image1.src="1.png";

I was just wondering if anyone knows of a way of resizing an image when it's drawn to the canvas, so that I could just a thumbnail sized image? 我只是想知道是否有人知道在将图像绘制到画布上时调整图像大小的方法,以便可以仅显示缩略图大小的图像?

Thanks in advance! 提前致谢!

I have tried adding parameters in to the drawImage function to resize the image, but this doesn't seem to have made any difference... 我尝试将参数添加到drawImage函数中以调整图像大小,但这似乎没有任何区别...

var image1 = new Image();

image1.onLoad = function(){
                context.drawImage(image1, 50, 50, 10, 10);
                };
            image1.src="1.png";

Are you using CSS to set the size of the canvas? 您是否正在使用CSS设置画布的大小? You need to set a height and width on the element instead or everything in your canvas will be scaled "unexpectedly". 您需要在元素上设置高度和宽度,否则画布中的所有内容都会“意外”缩放。 This could be your problem. 这可能是您的问题。

See Strange HTML5 Canvas drawImage behaviour 请参见奇怪的HTML5 Canvas drawImage行为

I had trouble finding the problem in your code... But I found it ! 我在您的代码中找不到问题...但是我找到了!

You gonna hate this : you wrote image.onLoad instead of image.onload... yes, javascript is case-sensitive . 您可能会讨厌:您编写了image.onLoad而不是image.onload ...是的, javascript区分大小写 :-) :-)

correct code is : 正确的代码是:

var image1 = new Image();

image1.onload = function(){
                context.drawImage(image1, 50, 50, 10, 10);
                };
            image1.src="1.png";

drawImage() takes additional width and height parameter: drawImage()需要附加的width和height参数:

   context.drawImage(image, x, y, width, heighT)

https://duckduckgo.com/?q=!mdn+drawimage https://duckduckgo.com/?q=!mdn+drawimage

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

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