Drawing a curved image on canvas using clipping
Written by Richard Heyes, RGraph author, on 2nd December 2023This article provides you with the source code for drawing a curved image on a canvas tag using clipping.
clip function here: https://www.rgraph.net/canvas/reference/clip.html). The code for the example is shown below and the comments in the code should provide you with some information about what it's doing.
>script<
// Get hold of the context so that we can draw
context = document.getElementById('cvs').getContext('2d');
//
// Load the image first. When it has loaded call the
// draw() function to draw the image. Then add some
// text.
//
var img = new Image();
img.src = '/images/page-blog-curved-image.png';
img.onload = function ()
{
// When the image has loaded - call the draw()
// function that draws the image on to the
// canvas
draw();
//
// Draw the text that you can see beneath the image.
// Despite being higher up in the code than the draw()
// function, this text is actually drawn last.
//
context.font = '26pt Arial';
context.textAlign = 'center';
context.fillText('A curved image!', 300,230);
};
//
// This is the main draw function that draws on the
// canvas
//
function draw()
{
//
// Save the canvas state before clipping so that
// it be reset after drawing has finished
//
context.save();
//
// Start a new path and draw the outline of the curved shape.
// This shape will not be immediately drawn on to the canvas -
// first we're going to clip to the shape and then draw the
// image. So the image will be constrained to the area within
// the shape. Only after the image has been drawn will the
// path that we're drawing here be stroked to the canvas in
// black (producing the black outline that you can see around
// the image).
//
context.beginPath();
context.moveTo(100,200);
context.lineTo(100,50);
context.quadraticCurveTo(300, 0, 500, 50);
context.lineTo(500,200);
context.quadraticCurveTo(300, 150, 100, 200);
context.closePath();
context.clip();
//
// Draw the image
//
context.drawImage(img,0,-40);
//
// Restore the canvas state now that the
// image has been drawn (effectively
// turning off clipping.
//
context.restore();
//
// Now that clipping has been turned off, stroke
// the path that was first made (ie what was defined
// to be the clip path to make the outline)
//
context.lineWidth = 3;
context.stroke();
}
</script>