How to fill a shape on mouseover using canvas? - javascript

I am trying to make a bowl shape and its content would gradually show as we go over it from bottom to top (and vice versa). here is my code for the bowl and the static filling.
I am new to canvas and to js animation.
Does anyone have an idea and can help me? Thank you :)
const canvas = document.createElement('canvas')
document.body.appendChild(canvas)
canvas.width = 800
canvas.height = 500
const ctx = canvas.getContext('2d')
ctx.fillStyle = 'white'
ctx.fillRect(0, 0, 800, 500)
const bowl = new Path2D()
bowl.arc(400, 390, 100, 0, Math.PI)
ctx.stroke(bowl)
ctx.moveTo(300,390)
ctx.lineTo(500,390)
ctx.stroke()
const fluid = new Path2D()
fluid.arc(400, 391, 99, 0, Math.PI)
ctx.fillStyle = 'red'
ctx.fill(fluid)

As I know, you can't do this directly on the item. I mean that you can't add event on the bowl because canvas retrieve the x and y coordinates and "draw" a perpendicular line to the shape to check if there are in the same axis.
Please see this post here How do I add a simple onClick event handler to a canvas element?
Think about use "over" event, because it doesn't work on touch devices.

Related

HTML Canvas - Adjust opacity of multiple elements as a layer [duplicate]

This question already has an answer here:
Is there a way to disable color mixing/overlapping in html canvas
(1 answer)
Closed 7 months ago.
I'm trying to find a way to draw multiple elements onto an HTML canvas, then adjust all of their opacities at once. For example, this codepen example draws two overlapping rectangles with globalAlpha set to 0.5, so they're semi-transparent.
Here's what I see:
Here's what I want to see:
In other words, I want to draw some set of elements, then adjust their alpha/opacity all at once. In the example above, I want the overlapping section of blue & red to appear as just blue, since the blue rectangle was drawn 2nd.
I want this solution to apply to images, shapes, any canvas drawings really.
Does anyone know how to accomplish this using HTML canvas?
you must decompose the process
1- create de canvas with all draw ( alpha 100%)
2 set aside the flattened drawings
3 clear the canvas
4 fetch the picture and add it to the canvas
5 set alpha to 50%
6 add the tmp flattened drawings with alpha
const cnv = document.createElement("canvas");
cnv.width = 300;
cnv.height = 300;
const ctx = cnv.getContext("2d");
document.body.appendChild(cnv);
// Draw red rectangle
ctx.fillStyle = "#f00";
ctx.fillRect(20, 20, cnv.width - 140, cnv.height - 60);
// Draw blue rectangle
ctx.fillStyle = "#00f";
ctx.fillRect(100, 40, cnv.width - 140, cnv.height - 60);
//aside the draw in flatten layer
let tmp = new Image();
tmp.src = cnv.toDataURL();
// clear the canvas
ctx.clearRect(0, 0, cnv.width, cnv.height);
// apply bg
ctx.fillStyle = "#000";
ctx.fillRect(0, 0, cnv.width, cnv.height);
const image = new Image(); // Using optional size for image
image.src = "https://img.photographyblog.com/reviews/kodak_pixpro_fz201/photos/kodak_pixpro_fz201_01.jpg";
image.onload = () => {
// Draw background image
ctx.drawImage(image, 0, 0);
ctx.drawImage(image, 0, 0, cnv.width, cnv.width);
// Set alpha to 0.5
ctx.globalAlpha = 0.5;
//overlay with the tmp flatten img with 50%
ctx.drawImage(tmp, 0, 0, cnv.width, cnv.width);
}

fillText on canvas keeps going behind the background

I'm using ctx.globalCompositeOperation = 'destination-over'. Though the text still goes behind.
Game.setup();
ctx = Game.context;
if (AllImagesLoaded === true) {
loading = false;
clearInterval(int);
BackgroundsA.push(true);
ctx.globalCompositeOperation = 'destination-over';
Interact = new text(window.innerWidth / 2, window.innerHeight / 2 - 200, 'Press F to Interact', 'white', '30px Verdana');
Sprites.push(new sprite(window.innerWidth / 2 - 275, window.innerHeight / 2 - 315, 'idle_jack/frame_1.PNG', 600, 600, 5));
Player = new component(window.innerWidth / 2, window.innerHeight / 2 - 100, 'rgba(0, 0, 0, 0)', 50, 150);
ctx.globalCompositeOperation = 'source-over';
Backgrounds.push(new background(0, 0, 'Backgrounds/Test/test2.jpg'));
ctx.globalCompositeOperation = 'destination-over';
The "new [KEYWORDS]" are functions for filling or drawing text/components/images.
Please help!
Why don't you draw everything from behind, i.e. firstly draw the backgrounds of the game, then text and at the end player and all of the game objects ?
However if you do want to draw everything like you're trying to now, then try changing global composite operation just before drawing, it's not clear if new Background() will actually draw the background or not from your code. Here is an article to read about global composite operation:
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation

How can I detect if a polygon(drawn in canvas) is clicked by me? [duplicate]

I've created a grid of several distorted rectangles made with Bezier curves. Each rectangle has its own color on the picture.
Let's say, I want to add hover effect for each of these rectangles, therefore I need to know its dimensions. Since I can fill or stroke the figure I assume that there is some way to get them, but I'm not sure.
Here is the example of the rectangles:
So the question is, is there some method in the canvas API with which I can achieve the desired effect?
Yes you can use isPointInPath(Path2D, x, y) method.
Note that if you don't use the Path2D object, you can also call it just with isPointInPath(x, y), but then it will check on the currently being drawn path (declared with beginPath()).
var ctx = canvas.getContext('2d');
var myPath = new Path2D();
myPath.bezierCurveTo(50, 100, 180, 10, 20, 10);
myPath.lineTo(50, 100);
function draw(hover) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = hover ? 'red' : 'green';
ctx.fill(myPath);
}
canvas.onmousemove = function(e) {
var x = e.clientX - canvas.offsetLeft,
y = e.clientY - canvas.offsetTop;
var hover = ctx.isPointInPath(myPath, x, y)
draw(hover)
};
draw();
<canvas id="canvas"></canvas>

Reveal image on canvas with draw/strokes/paint

I want to achive the following:
Draw a bg-image to the canvas (once or if needed repeatedly)
The image should not be visible at the beginning
While i "paint" shapes to the canvas the bg-image should get visible where the shapes were drawn
The parts of the image that will be revealed shall be "painted" (like with a brush) so i want to use strokes.
What i tried:
- Do not clear the canvas
- Paint rects to the canvas with globalCompositeOperation = 'destination-in'
This works, the rectangles reveal the image but i need strokes
If i use strokes they are ignored with 'destination-in' while i see them with normal globalCompositeOperation.
Is this intended that the strokes are ignored? Is there a workaround like somehow converting the stroke/shape to a bitmap? Or do i have have to use two canvas elements?
In OpenGL i would first draw the image with its rgb values and with a = 0 and then only "paint" the alpha in.
You can solve it by these steps:
Set the image as a pattern
Set the pattern as fillStyle or strokeStyle
When you now fill/stroke your shapes the image will be revealed. Just make sure the initial image fits the area you want to reveal.
Example showing the principle, you should be able to adopt this to your needs:
var ctx = canvas.getContext("2d"),
img = new Image,
radius = 40;
img.onload = setup;
img.src = "http://i.imgur.com/bnAEEXq.jpg";
function setup() {
// set image as pattern for fillStyle
ctx.fillStyle = ctx.createPattern(this, "no-repeat");
// for demo only, reveals image while mousing over canvas
canvas.onmousemove = function(e) {
var r = this.getBoundingClientRect(),
x = e.clientX - r.left,
y = e.clientY - r.top;
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.arc(x, y, radius, 0, 2*Math.PI);
ctx.fill();
};
}
<canvas id=canvas width=900 height=600></canvas>
Hope this helps!
Alternative solution:
Put the image as a normal image on your website
add a canvas and use CSS positioning to place it right above the image
Fill the canvas with the color you use as the page background
have your paint tools erase the canvas when you draw. By the way, you can set context.globalCompositionOperation = 'destination-out' to turn all drawing operations into an eraser.
Here is an example. As you can see, the alpha properties of your tools are respected.
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
//prepare canvas
ctx.fillStyle = '#ffffff'
ctx.fillRect(0, 0, 120, 120);
//prepare a 30% opacity eraser
ctx.globalCompositeOperation = 'destination-out';
ctx.lineWidth = 5;
ctx.strokeStyle = 'rgba(0, 0, 0, 0.3)';
// make random strokes around cursor while mouse moves
canvas.onmousemove = function(e) {
var rect = this.getBoundingClientRect();
var x = e.clientX - rect.left;
var y = e.clientY - rect.top;
ctx.beginPath();
ctx.moveTo(x + Math.random() * 33 - 16, y + Math.random() * 33 - 16);
ctx.lineTo(x + Math.random() * 33 - 16, y + Math.random() * 33 - 16);
ctx.stroke();
}
<span>Move your mouse:</span>
<div>
<img src='https://upload.wikimedia.org/wikipedia/commons/thumb/6/61/HTML5_logo_and_wordmark.svg/120px-HTML5_logo_and_wordmark.svg.png' style='position:absolute'>
<canvas id='canvas' width=120 height=120 style='position:absolute'></canvas>
</div>

Html5 Canvas: alternative for drawImage()

Since I faced some rounding issues* with the default scale()-function of canvas I've implemented my own matrix-transformations for canvas. This is working fine with a sole exception, I cannot rotate an image because the drawImage() function can only be parameterized with the top left corner of the picture.
Is there any other method to draw an image on a canvas? A method that can be parameterized with at least the coordinates for the top, left and the bottom right corner?, so that I can manually rotate the coordinates?
*The issue is a one-pixel-gap between shapes after scaling by a factor < 1.
Based off of your fiddle in the comments you could use an in memory canvas as a back buffer to draw what you need to at normal size, then scale the context of your main canvas and use drawImage to draw the scaled result.
Live Demo
var canvas = document.getElementById('c');
var context = canvas.getContext('2d');
var backBuffer = document.createElement("canvas"),
bCtx = backBuffer.getContext("2d");
paint = function (x, y, scale) {
bCtx.clearRect(0,0,backBuffer.width,backBuffer.height);;
bCtx.beginPath();
bCtx.rect(x, y, 30, 30);
bCtx.fillStyle = 'black';
bCtx.fill();
bCtx.beginPath();
bCtx.rect(x + 30, y, 30, 30);
bCtx.fillStyle = 'black';
bCtx.fill();
context.save();
context.scale(scale,scale);
context.drawImage(backBuffer,0,0);
context.restore();
}
paint(10, 10, 1);
paint(10, 70, .66);

Categories

Resources