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
You can try this code. I hope this will help you
This code assigned image size to canvas.
As all images are coming in 2D so the canvas size must be either square or rectangle.
Basic shape
The canvas can be any shape if you use the alpha (transparency) channel to make unwanted pixels transparent.
Example
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
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.