Canvas Image Example
Canvas is a powerful HTML element that allows you to draw graphics via JavaScript. It's widely used in web development for creating interactive visuals, animations, and games. Let's explore canvas image examples to understand its capabilities better.
Before diving into examples, ensure you have a basic understanding of the canvas API. It consists of methods like drawImage, fillRect, strokeRect, and arc for drawing shapes, images, and paths.
Basic Canvas Image Examples
Let's start with some fundamental canvas image examples.
First, include the canvas element in your HTML:
<canvas id="myCanvas" width="500" height="500"></canvas>
Drawing an Image
To draw an image onto the canvas, use the drawImage method:
var ctx = document.getElementById('myCanvas').getContext('2d');
var img = new Image();
img.src = 'path/to/image.jpg';
img.onload = function() {
ctx.drawImage(img, 0, 0);
};
Adding Text
You can also add text to your canvas using the fillText method:
ctx.font = '30px Arial';
ctx.fillText('Hello, Canvas!', 10, 50);
Interactive Canvas Image Examples
Canvas shines when creating interactive visuals. Here are two engaging examples.
Dragging an Image
Let's create a simple image drag-and-drop functionality:
var img = new Image();
img.src = 'path/to/image.jpg';
img.onload = function() {
ctx.drawImage(img, 0, 0);
img.x = 0;
img.y = 0;
canvas.addEventListener('mousedown', function(e) {
img.x = e.offsetX;
img.y = e.offsetY;
});
canvas.addEventListener('mousemove', function(e) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, e.offsetX - img.x, e.offsetY - img.y);
});
};
Animating an Image
Canvas is perfect for creating animations. Here's a simple rotating image example:
var img = new Image();
img.src = 'path/to/image.jpg';
img.onload = function() {
var angle = 0;
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.save();
ctx.translate(canvas.width / 2, canvas.height / 2);
ctx.rotate(angle);
ctx.drawImage(img, -img.width / 2, -img.height / 2);
ctx.restore();
angle += 0.1;
requestAnimationFrame(draw);
}
draw();
};
Canvas offers endless possibilities for creating stunning visuals and interactive experiences. Start exploring its API and experiment with different shapes, images, and animations. Happy coding!