0

I am a beginner on canvas and I have a question: I have a background that I don’t want to change but I would like to switch a picture vertically (upside down). I would like to be able to turn my character (a turtle) upside down at some points during my animation Can Somebody help me, please

This is a part of my code

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

var imgbackground = new Image();
img.src = 'BG.png';
ctx.drawImage(img, 0, 0, 457, 542);

var turtle = new Image(); // My character
turtle.src = 'turtle.png';
ctx.drawImage(turtle, 0, 0, 457, 542);

function gameTime (){
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(imgbackground, 0, 0, 900, 500);
    ctx.drawImage(turtle, 0, 0, 900, 500);

    window.requestAnimationFrame(gameTime)

}
window.requestAnimationFrame(gameTime)

1 Answers1

-1

So you can use scale(1, -1) to flip something vertically:

var canvas = document.getElementById('myCanvas')
var context = canvas.getContext('2d');
context.scale(1, -1);

The important part being the .scale which is flipping the Y value with -1, context here would be the element, so change that to your required element.

 so try turtle.scale(1, -1)

- To flip your lovely turtle.

You can also flip things horizontally with (-1, 1) - affecting the x value.

Sparlarva
  • 790
  • 1
  • 8
  • 30