M
M
Mikhail Pakhmutov2014-01-02 05:57:58
Canvas
Mikhail Pakhmutov, 2014-01-02 05:57:58

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

3 answer(s)
S
Sergey Melnikov, 2014-01-02
@mlnkv

maybe you should read about canvas and see what others are doing on canvas? Or is reading and googling not an option?

E
Eugene, 2014-01-03
@Eugene22

Not entirely clear, but try trying sprites

P
personaljs, 2014-01-03
@personaljs

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);

https://developer.mozilla.org/samples/canvas-tutor...
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 question

Ask a Question

731 491 924 answers to any question