将html img元素转换为画布 [英] Convert html img element to canvas

查看:207
本文介绍了将html img元素转换为画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有html页,内容为

<div class="span12">
    <img id="myImg" src="myImage.png" style="max-width: 100%; height: auto;" />
</div>

,其中myImage.png的实际大小为1600 * 900.图像的尺寸为796 * 448(拉伸后保持宽高比).

where the actual size of myImage.png is 1600 * 900. The image is rendered with size 796 * 448 (streched keeping the aspect ratio).

我正在尝试使用javascript作为

function convertImgToCanvas(){
    var myImgElement = document.getElementById("myImg");
    var myCanvasElement = document.createElement("canvas");
    myCanvasElement.width = myImgElement.width;
    myCanvasElement.height = myImgElement.height;
    var context = myCanvasElement.getContext('2d');
    context.drawImage(myImgElement,0,0);    
}

生成的画布的尺寸为1600 * 900,而不是796 * 448.我期望画布的大小为796 * 448.

The resulting canvas has a size 1600 * 900, not 796 * 448. I am expecting the size of canvas to be 796 * 448.

如果将画布的高度和宽度设置为

If I set the height and width of canvas as

myCanvasElement.width = '796px';
myCanvasElement.height = '448px';

画布的尺寸变为796 * 448,但图像被裁剪

the size of canvas become 796 * 448, but image is cropped

是否有任何解决方案可以从img元素创建canvas,其宽度和高度与img元素的宽度和高度完全相同,而不会裁剪图像?

Is there any solution to create a canvas from img element, with exactly same width and height as that of img element, without cropping the image ?

推荐答案

您没有正确使用drawImage.参见此处: https://developer.mozilla.org/zh- US/docs/Web/API/CanvasRenderingContext2D/drawImage

You're not using drawImage correctly. See here: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage

第三个示例允许您指定源和目标的x,y,width和height参数:ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);

The third example allows you to specify x,y,width and height parameter of both source and destination: ctx.drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight);

因此,最简单的解决方法是:

So the easiest fix in your case would be something like:

context.drawImage(myImgElement, 0, 0, 1600, 900, 0, 0, 796, 448);  

这是实际的操作(由于大小原因,请全页显示):

And here it is in action (go Full Page because of the size):

function convertImgToCanvas(){
    var myImgElement = document.getElementById("myImg");
    var myCanvasElement = document.createElement("canvas");
    // don't forget to add it to the DOM!!
    document.body.appendChild(myCanvasElement); 
    myCanvasElement.width = 796;
    myCanvasElement.height = 448;
    var context = myCanvasElement.getContext('2d');
    context.drawImage(myImgElement, 0, 0, 1600, 900, 0, 0, 796, 448);
    // remove the image for the snippet
    myImgElement.style.display = 'none';
}

convertImgToCanvas();

<div class="span12">
    <img id="myImg" src="https://upload.wikimedia.org/wikipedia/commons/0/08/Ice-and-Fire-showdown_1600x900.jpg" style="max-width: 100%; height: auto;" />
</div>

这篇关于将html img元素转换为画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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