user1546022
user1546022

Reputation: 183

JS resize image then save the resized one

I am working on a JS game that uses large images. I want to be able to shrink them before the game starts (while loading) to fit the size of the canvas. Looking online the only way I found to resize an image is through drawImage, but I noticed that if I shrink an image through drawImage the performance will not be improved. Even though a shrinked image should draw faster. So I wrote this script to resize an image before hand but there seems to be a problem with it.

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var resizeImage = function (img, newWidth, newHeight) {
    var image = new Image();
    var tempCanvas = document.createElement('canvas');
    var tempContext;

    tempCanvas.id = 'tempCanvas';
    tempCanvas.width = newWidth;
    tempCanvas.height = newHeight;
    tempCanvas.style.visibility = 'hidden';

    document.body.appendChild(tempCanvas);

    tempContext = tempCanvas.getContext('2d');
    tempContext.drawImage(img, 0, 0, newWidth, newHeight);
    image.src = tempCanvas.toDataURL("image/png");
    return image;
};

var img = new Image();
var resizedImg;
img.onload = function () {
    resizedImg = resizeImage(this, this.width / 4, this.height / 4);
    resizedImg.onload = function () {
        ctx.drawImage(resizedImg, 0, 0);
    }
};
img.src = "https://upload.wikimedia.org/wikipedia/en/3/39/Wakerlink.jpg";

I expected to see the resized image drawn but I am getting nothing.

Upvotes: 0

Views: 177

Answers (2)

Tschallacka
Tschallacka

Reputation: 28722

tempCanvas.style.visibility = 'hidden';

That would possibly give you issues.

I suggest you make a wrapper div over your game play relatively positioned Then add this canvas absosolutely positioned and then give it a negative z-index so it will dissapear behind the canvas but technically still be visible.

 <div style='position:relative'>
    <canvas id='forresize' style="z-index:-100;position;absoulte;top:0p;left:0px;">
    </canvas>
    <div id='wrapper' style='position:absolute;top:0px;left:0px;width:100%;height:100%;">
         Your game divs/elements here
    </div>
 </div>

Upvotes: 0

Niddro
Niddro

Reputation: 1725

The problem lies with using an external (not on the same server as your script) image together with toDataURL(), which is not allowed. Thus the error message:

Uncaught SecurityError: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.

Upvotes: 2

Related Questions