ank5
asked on
HTML 5 canvas - stretch image to the canvas width and height
In my ionic app, I am using HTML 5 canvas to load a image which is already on the device. The goal is to have users annotate the image and then save it back to the device.
The Canvas spans the whole device screen, however the image occupies only a small portion on the top left.
Here is my canvas code
then in the controller
This does load the image, however, it does not cover the complete canvas. Image just occupies a very small area on the top left corner of the canvas.
How can I ensure that the image covers the complete canvas? I have tried setting the width and height parameters in drawImage but that did not help.
The Canvas spans the whole device screen, however the image occupies only a small portion on the top left.
Here is my canvas code
<ion-content overflow-scroll="true" has-bouncing="false" padding="true" class="has-header">
<ion-content has-bouncing="false" scroll="false" style="position: fixed">
<canvas id="canvas" autogram offset="88" color="{{ color }}"></canvas>
</ion-content>
</ion-content>
then in the controller
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var img = new Image();
img.src = $stateParams.imageId;
img.onload = function() {
context.drawImage(img, 0, 0, canvas.width, canvas.height);
}
This does load the image, however, it does not cover the complete canvas. Image just occupies a very small area on the top left corner of the canvas.
How can I ensure that the image covers the complete canvas? I have tried setting the width and height parameters in drawImage but that did not help.
ASKER
Still the same result
I cannot test but check this please:
img.width=window.innerWidth;
img.height=window.innerHeight;
if that does not work then check this:
var mycanvas = document.getElementById('canvas');
var context = mycanvas.getContext('2d');
var img = new Image();
img.src = $stateParams.imageId;
img.onload = function() {
img.width = mycanvas.offsetWidth;
img.height = mycanvas.offsetHeight;
context.drawImage(img, 0, 0, mycanvas.width, mycanvas.height);
}
ASKER
This didn't help either. What worked though was providing width and height in the canvas tag
I would like to avoid doing this and set it dynamically. Can't make out why changes in Javascript related to width and height are not having any impact.
<canvas id="canvas" color="{{ color }}" width="800" height="600" style="position:relative;"></canvas>
'I would like to avoid doing this and set it dynamically. Can't make out why changes in Javascript related to width and height are not having any impact.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Open in new window