How to turn an html canvas into an image and then draw that canvas onto the canvas

60 views Asked by At

I'm currently working on an html canvas javascript game, and it's just about finished, but I want to scale up the canvas so the whole game is bigger. I tried using something like

var imgData = ctx.getImageData(0, 0, 300, 500);

ctx.putImageData(imgData,0,0,0,0,360,600)

but using this method I couldn't increase the size of the image. What is the best method for this?

1

There are 1 answers

0
Ryan Grube On

There are multiple ways you can achieve this, the two that i've experimented with would use 2 seperate canvases, putImageData is a little weird, and does not work well for scaling up, what i would recommend, is have a separate canvas, the size of the scaled up version, and then use ctx.drawImage to draw the first canvas on the scaled up version:

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

var c2 = document.getElementById('c2');
var ctx2 = c2.getContext('2d')

ctx.fillStyle = "red";
ctx.fillRect(10,10,100,100)

var scaleX = c2.width / c.width;
var scaleY = c2.height / c.height;

ctx2.drawImage(c,0,0,c2.width,c2.height)
canvas{
  border: 2px solid black
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <canvas id="c" width="200" height="200"></canvas>
    <canvas id="c2" width="400" height="400" ></canvas>
    <script src="script.js"></script>
  </body>
</html>

The other way is to just scale up the context, then draw the image at 0,0, with no width or height specified:

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

var c2 = document.getElementById('c2');
var ctx2 = c2.getContext('2d')

ctx.fillStyle = "red";
ctx.fillRect(10,10,100,100)

var scaleX = c2.width / c.width;
var scaleY = c2.height / c.height;

ctx2.scale(scaleX,scaleY)
ctx2.drawImage(c,0,0)
ctx2.scale(1/scaleX,1/scaleY)
canvas{
  border: 2px solid black
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <canvas id="c" width="200" height="200"></canvas>
    <canvas id="c2" width="400" height="400" ></canvas>
    <script src="script.js"></script>
  </body>
</html>

One more option is to use the css scale() tag, but that messes with mouse clicks, and is really annoying so i wouldn't do that. Keep in mind, all methods that scale up the canvas (unless your scaling up coordinates and redrawing), will result in blur.

Hope this helps :D