skip to Main Content

I have created a HTML Canvas and everywhere I have checked it has some width and height but I want my canvas to be of some shape for e.g. a Star or any other png image that can be converted into a canvas. I have tried few things like

<canvas class="question" id="canvas"></canvas>
<img src="img/11.png" id="scream">

<script>
var canvas = document.getElementById("canvas");
canvas.width = 200;
canvas.height = 200;
var ctx = canvas.getContext("2d");
var img = document.getElementById("scream");
ctx.drawImage(img, 0, 0);
</script>

but all it does is it makes a canvas of sqaure shape with an image in it. I want the canvas to be shaped like the image.

2

Answers


  1. You can try this code. I hope this will help you

        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        var img = document.getElementById("scream");
        canvas.width = img.width;
        canvas.height = img.height;
        ctx.drawImage(img, 0, 0);
    

    This code assigned image size to canvas.
    As all images are coming in 2D so the canvas size must be either square or rectangle.

    Login or Signup to reply.
  2. Basic shape

    The canvas can be any shape if you use the alpha (transparency) channel to make unwanted pixels transparent.

    Example

        // draw image on canvas    
        const ctx = canvas.getContext("2d", {alpha: true}); // alpha option is the default
                                                            // I added it to show my intent
        canvas.width = scream.width;
        canvas.height = scream.height;
        ctx.drawImage(scream, 0, 0);
    

    Once the image is drawn on the canvas you can keep pixels by drawing over them using the globalCompositeOperation = "destination-in".

    For example the following will make the canvas circular

        // draw a circle removing pixels outside the circle
        ctx.globalCompositeOperation = "destination-in";
        ctx.beginPath();
        const radius = Math.min(canvas.width, canvas.height) * 0.5;
        ctx.arc(canvas.width * 0.5, canvas.height * 0.5, radius, 0. Math.PI * 2);
        ctx.fill();
        ctx.globalCompositeOperation = "source-over";  // restore default comp op
    

    You can draw any shape, or use an image (eg SVG) to define the shape.

    Interactive shape

    If you need the canvas to interact with pointer / mouse events that need to be aware of the shape use CSS clip-path to define the shape.

    Example using clip-path.

        const ctx = canvas.getContext("2d");
        canvas.width = scream.width;
        canvas.height = scream.height;
        ctx.drawImage(scream, 0, 0);
        const radius = Math.min(canvas.width, canvas.height) * 0.5;
        canvas.style.clipPath = "circle(" + radius + "px)";
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search