Answer the question
In order to leave comments, you need to log in
How to implement the rendering of objects of complex shape using HTML5 Canvas?
Hello. I want to try my hand at developing a game to explore the possibilities of HTML5.
Question 0:
Is it possible to create canvas objects of complex shapes by loading them from a png file with only non-transparent areas being interpreted?
Question 1:
For example, we uploaded an oval-shaped object (500x300px). Is it possible to cut off a part of an arbitrary shape from it (hitting a bullet shot into an object)?
Answer the question
In order to leave comments, you need to log in
maybe you should read about canvas and see what others are doing on canvas? Or is reading and googling not an option?
You can use a black and white image as a mask using 'source-in' globalCompositeOperation. First you draw your mask image to the canvas, then you change the globalCompositeOperation to 'source-in', finally you draw your final image.
Your final image will only be drawn where it overlay the mask.
var ctx = document.getElementById('c').getContext('2d');
ctx.drawImage(YOUR_MASK, 0, 0);
ctx.globalCompositeOperation = 'source-in';
ctx.drawImage(YOUR_IMAGE, 0 , 0);
var dimensions = {width: XXX, height: XXX}, //your dimensions
imageObj = document.getElementById('#image'), //select image for RGB
maskObj = document.getElementById('#mask'), //select B/W-mask
image = imageObj.getImageData(0, 0, dimensions.width, dimensions.height),
alphaData = maskObj.getImageData(0, 0, dimensions.width, dimensions.height).data; //this is a canvas pixel array
for (var i = 3, len = image.data.length; i < len; i = i + 4) {
image.data[i] = alphaData[i-1]; //copies blue channel of BW mask into A channel of the image
}
//displayCtx is the 2d drawing context of your canvas
displayCtx.putImageData(image, 0, 0, 0, 0, dimensions.width, dimensions.height);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question