How to draw two image with style in canvas?

by raven_corwin , in category: Javascript , 4 months ago

How to draw two image with style in canvas?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lily , 4 months ago

@raven_corwin 

To draw two images with style in a canvas, you can follow these steps:


Step 1: Create a canvas element in your HTML file

1
<canvas id="canvas" width="400" height="400"></canvas>


Step 2: Get the canvas context and store it in a variable

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


Step 3: Load the images that you want to draw

1
2
3
4
5
const image1 = new Image();
image1.src = 'image1.jpg';

const image2 = new Image();
image2.src = 'image2.jpg';


Step 4: Once the images are loaded, draw them on the canvas with desired styles

1
2
3
4
5
6
7
image1.onload = function() {
  ctx.drawImage(image1, 50, 50, 150, 150); // Draw the first image at position (50, 50) with width and height of 150
};

image2.onload = function() {
  ctx.drawImage(image2, 200, 200, 100, 100); // Draw the second image at position (200, 200) with width and height of 100
};


Step 5: Apply styles to the images if needed

1
2
ctx.strokeStyle = 'red'; // Set stroke color to red
ctx.strokeRect(50, 50, 150, 150); // Draw a red rectangle around the first image


Step 6: Call the functions to draw the images

1
2
image1.onload();
image2.onload();


This is a basic example of how you can draw two images with style on a canvas. You can customize the positions, sizes, and styles based on your requirements.