Last active
April 27, 2020 13:30
-
-
Save sandrabosk/c39e75e730a2c4ac8080af24838b0cb4 to your computer and use it in GitHub Desktop.
solution-canvas-image-text
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
console.log('I am connected!'); | |
const theCanvas = document.getElementById('canvas'); | |
const ctx = theCanvas.getContext('2d'); | |
// create new image object | |
const img = new Image(); | |
// "src" has to point as the image is used in HTML file | |
img.src = | |
'https://blog.ironhack.com/wp-content/uploads/2018/11/ironhack-logo-150x150.png'; | |
// set the start position of our image | |
let imgX = 0; | |
let imgY = 0; | |
ctx.fillStyle = 'red'; | |
ctx.font = '15px monospace'; | |
ctx.fillText('Hello! 🥁', 90, 150); | |
function moveImg(x, y) { | |
// instead working with raw numbers (in our case width=300 and height=300 from canvas tag in index.html) | |
// we can access those properties through "theCanvas" object | |
const width = theCanvas.width; | |
const height = theCanvas.height; | |
// clears whole canvas to simulate animation (==movement) of the object (image) | |
ctx.clearRect(0, 0, width, height); | |
ctx.fillText('Hello! 🥁', 90, 150); | |
// ctx.drawImage(whichImage, x, y, width, height); | |
ctx.drawImage(img, imgX, imgY, 50, 50); | |
// changes position of X coordinate | |
imgX += 3; | |
// if x is divisible with 10, move y for 5 pixels as well | |
if (imgX % 10 === 0) { | |
imgY += 5; | |
} | |
// calls itself every 30ms => RECURSIVE FUNCTION | |
setTimeout(() => moveImg(imgX, imgY), 30); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8" /> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge" /> | |
<title>Canvas Images and Text</title> | |
<link rel="stylesheet" href="styles/style.css" /> | |
</head> | |
<body> | |
<canvas id="canvas" width="300" height="300"></canvas> | |
<button onclick="moveImg(0, 0)">Move Image</button> | |
<!-- add js file in the end when the DOM is already loaded --> | |
<script src="js/index.js"></script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment