Link to home
Start Free TrialLog in
Avatar of ank5
ank5Flag for India

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

 <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>

Open in new window


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);
        } 

Open in new window


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.
Avatar of Zvonko
Zvonko
Flag of North Macedonia image

Set the width and height of the img after onload:
img.onload = function() {
                 img.width = canvas.width;
                 img.height= canvas.height;
                  context.drawImage(img, 0, 0, canvas.width, canvas.height);
        } 

Open in new window

Avatar of ank5

ASKER

Still the same result
I cannot test but check this please:
img.width=window.innerWidth; 
img.height=window.innerHeight;

Open in new window

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);
		}

Open in new window

Avatar of ank5

ASKER

This didn't help either. What worked though was providing width and height in the canvas tag

<canvas id="canvas" color="{{ color }}" width="800" height="600" style="position:relative;"></canvas>

Open in new window

'

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
Avatar of Zvonko
Zvonko
Flag of North Macedonia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial