Convert Html Img Element To Canvas
I have html page with content as where the actual siz
Solution 1:
You're not using drawImage
correctly. See here: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage
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):
functionconvertImgToCanvas(){
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();
<divclass="span12"><imgid="myImg"src="https://via.placeholder.com/1600x900"style="max-width: 100%; height: auto;" /></div>
Solution 2:
You can do it with scale.
functionconvertImgToCanvas(){
var myImgElement = document.getElementById("myImg");
var myCanvasElement = document.createElement("canvas");
myCanvasElement.width = myImgElement.width;
myCanvasElement.height = myImgElement.height;
var context = myCanvasElement.getContext('2d');
context.scale(myCanvasElement.width / myImgElement.width, myCanvasElement.height / myImgElement.height);
context.drawImage(myImgElement, 0, 0);
}
Solution 3:
Check link given below. You can convert image to HTML5 canvas element: http://lab.abhinayrathore.com/img2canvas/
Post a Comment for "Convert Html Img Element To Canvas"