Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

124
Views
How do I set a border for player.png on background.png

I need to set a border on background.png so player.png cant go past it or off of it. I used JS and HTML. Everything else works just fine, please answer as soon as possible. :)

Here is my code:

Javascript:

var canvas = document.getElementById('myCanvas');

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

var background = new Image();
background.src = "images/background.png";
background.onload = function() {
    ctx.drawImage(background, 0, 0, canvas.width, canvas.height);
    start();
}

var image = new Image();
var imageX = 0;
var imageY = 0;

function start(){
    image.src = "images/player.png";
    image.onload = function(){
        imageX = 35;
        imageY = 35;
        ctx.drawImage(image, imageX, imageY);
    };
}

document.addEventListener("keydown", keyDownHandler);

function keyDownHandler(event){

    event.preventDefault();
    event.stopPropagation();

    if (event.keyCode == 65) {
        imageX -= 13;
    } else if (event.keyCode == 87) {
        imageY -= 13;
    } else if (event.keyCode == 68) {
        imageX += 13;
    } else if (event.keyCode == 83) {
        imageY += 13;
    }  
    redraw();
}
function redraw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.drawImage(background, 0, 0, canvas.width, canvas.height);
    ctx.drawImage(image, imageX, imageY);
}

Html:

<!DOCTYPE html>
<html>
  <head>
    <title>blow shoot</title>
  </head>
  <body>
    <canvas id= "myCanvas" width= "500" height= "250">
    <script src="main.js"></script>
</canvas>
  </body>
</html> 

Images:

player.png

background.png

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can add a strokeRect function:

ctx.strokeRect(x,y,w,h)

where x,y is the coordinate of the left upper corner of the image, and the w,h is the dimension of the image. If you want to make it stay out, -1 on x,y +2 on w,h to have a 1px offset on every side.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!