HTML5 canvas rendering- path clipping - javascript

In My case i have performed path clipping and then draw a image in clipped region. But it does not working.
here my code.`
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var x = canvas.width / 2;
var y = canvas.height / 2;
var radius = 75;
var offset = 50;
/*
* save() allows us to save the canvas context before
* defining the clipping region so that we can return
* to the default state later on
*/
context.save();
context.beginPath();
context.arc(x, y, radius, 0, 2 * Math.PI, false);
context.clip();
var imageObj = new Image();
imageObj.onload = function() {
context.drawImage(imageObj, 69, 50);
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth- vader.jpg';
</script>
</body>
</html>
Now image render without clipping.
Please share your valuable key to do this.

Related

Saturate image where mouse is hovering

I'm trying to have an image on my website become saturated at the same location the mouse is. When the mouse moves the saturation effect goes with it, and the area previously hovered over becomes grayscale again. I'm thinking this effect could be accomplished using saturate(), however I haven't had any success with it. Additionally, I would like the effect to be circular without hard edges similar to this.
Example of what it would look like (orange arrow indicating where the mouse is).
Any help or insight would be appreciated, thanks!
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content= "width=device-width, initial-scale=1.0" />
</head>
<script>
const size = 250;
var radius = 30;
var rad = Math.PI / 180;
var canvas = document.querySelector("canvas")
var ctx = canvas.getContext("2d");
canvas.width = size;
canvas.height = size;
var image = new Image();
image.onload = demo
image.src = "https://picsum.photos/250"
function draw_circle(x, y, radius) {
ctx.clearRect(0, 0, size, size);
ctx.drawImage(image, 0, 0); // image to change
ctx.globalCompositeOperation = "saturation";
ctx.beginPath();
ctx.fillStyle = "hsl(0,100%,50%)"; // saturation at 100%
ctx.arc(x, y, radius, 0, 360 * rad, false);
ctx.fill()
ctx.closePath();
ctx.globalCompositeOperation = "source-over"; // restore default comp
}
function demo() {
ctx.drawImage(image, 0, 0); // image to change
canvas.addEventListener('mousemove', function(ev) {
var cx = ev.offsetX
var cy = ev.offsetY
draw_circle(cx, cy, radius)
})
}
</script>
<canvas></canvas>
</html>
Using a canvas we can try. Here's a start inspired by How can I adjust the huse, saturation, and lightness of in image in HTML5 Canvas?.
const size = 250;
var radius = 30;
var rad = Math.PI / 180;
var canvas = document.querySelector("canvas")
var ctx = canvas.getContext("2d");
canvas.width = size;
canvas.height = size;
var image = new Image();
image.onload = demo
image.src = "https://picsum.photos/250"
function draw_circle(x, y, radius) {
ctx.clearRect(0, 0, size, size);
ctx.drawImage(image, 0, 0); // image to change
ctx.globalCompositeOperation = "saturation";
ctx.beginPath();
ctx.fillStyle = "hsl(0,100%,50%)"; // saturation at 100%
ctx.arc(x, y, radius, 0, 360 * rad, false);
ctx.fill()
ctx.closePath();
ctx.globalCompositeOperation = "source-over"; // restore default comp
}
function demo() {
ctx.drawImage(image, 0, 0); // image to change
canvas.addEventListener('mousemove', function(ev) {
var cx = ev.offsetX
var cy = ev.offsetY
draw_circle(cx, cy, radius)
})
}
<canvas></canvas>
This is a simple answer (change the logic of the program as you want):
<!DOCTYPE html>
<html>
<head>
<style>
div.relative {
position: relative;
width: 200px;
height: 150px;
}
.image {
width: 100%;
height: 100%;
}
</style>
<script>
const width = 50;
const height = 50;
function create() {
const element = document.createElement("div");
element.id = "filtered";
element.style.width = `${width}px`;
element.style.height = `${height}px`;
element.style.borderRadius = "50%";
element.style.position = "absolute";
element.style.backgroundColor = "red";
element.style.opacity = "0.2";
element.style.zIndex = "2";
return element;
}
function changePos(e) {
x = e.clientX;
y = e.clientY;
let element = document.getElementById("filtered");
if (!element) {
element = create();
document.getElementById("focusArea").appendChild(element);
}
element.style.left = `${x - width / 2}px`;
element.style.top = `${y - height / 2}px`;
}
function removeElement() {
if (document.getElementById("filtered")) {
document.getElementById("filtered").remove();
}
}
</script>
</head>
<body>
<div
id="focusArea"
onmouseleave="removeElement()"
onmousemove="changePos(event)"
class="relative"
>
<img
src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/800px-Image_created_with_a_mobile_phone.png"
class="image"
/>
</div>
</body>
</html>

javascript, controlling a ball's movement using mouse

I was following this MDN tutorial:
https://developer.mozilla.org/es/docs/Games/Workflows/Famoso_juego_2D_usando_JavaScript_puro/Mueve_la_bola
And I was wondering how could we control the ball's movement using mouse movement event.
I have seen that mousemove works with textarea and some inputs:
https://developer.mozilla.org/en-US/docs/Web/Events/mousemove
I thought if we could put a textarea behind the canvas, we could detect the event, get the mouse's position and let the user change the ball's movement with mouse movement.
I have read:
Dynamically resize textarea width and height to contain text
So I tried:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Juego</title>
<style>
* {
padding: 0;
margin: 0;
}
canvas {
background: #eee;
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<textarea name="ta" id="ta" cols="30" rows="10"></textarea>
<canvas id="myCanvas" width="480" height="320"></canvas>
<script>
const textarea = document.getElementById('ta');
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
textarea.style.height = canvas.height;
textarea.style.width = canvas.width;
let x = canvas.width / 2;
let y = canvas.height - 30;
const dx = 2;
const dy = -2;
let drawBall = function () {
ctx.beginPath();
ctx.arc(x, y, 10, 0, Math.PI * 2);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
};
function draw(e) {
console.log(e);
ctx.clearRect(0,0,canvas.width,canvas.height);
drawBall();
x += dx;
y += dy;
}
setInterval(draw, 10);
canvas.addEventListener('mousemove', draw);
</script>
</body>
</html>
The expected output would be to have the textarea using canvas' width and height, and being behind it; however it is smaller and put on top left:
Thank you for your help.
you don't need the textarea to capture the event, and it'll be complicated because the canvas will be on top and the textarea will never know the mouse is moving on top of it, and to make the ball moving with the mouse, you have to passe the x and y of the mouse to the draw(); while it's moving function
here's a fiddle : https://jsfiddle.net/vqdyLx5u/22/
let canvas = document.getElementById('myCanvas');
let ctx = canvas.getContext('2d');
function drawBall(x, y) {
ctx.beginPath();
ctx.arc(x, y, 10, 0, Math.PI * 2);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
function draw(x, y) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall(x, y);
}
draw(canvas.height / 2 , canvas.width / 2); // initial draw
canvas.addEventListener('mousemove', function(e) {
draw(e.pageX, e.pageY); // the coordinates of the mouse
});
* {
padding: 0;
margin: 0;
}
canvas {
background: #eee;
display: block;
margin: 0 auto;
}
<canvas id="myCanvas" width="480" height="320"></canvas>

Avoiding Javascript Memory Leaks from the Creation of Canvas

I have some HTML and Javascript code that draws a 2D canvas in the page. In the task manager, I can see memory increasing rapidly until the web page freezes.
Please let me know how I can prevent memory leaks or provide me with some alternative code that is able to draw canvas on the browser without creating such leaks.
function setup() {
// insert setup code here
}
function draw() {
// insert drawing code here
var canvas = document.createElement('canvas');
canvas.id = "CursorLayer";
canvas.width = 1224;
canvas.height = 600;
canvas.style.zIndex = 8;
canvas.style.position = "absolute";
canvas.style.border = "1px solid";
document.body.appendChild(canvas);
var c2 = canvas.getContext('2d');
var centerX=canvas.width/2-100;
var centerY=canvas.height/2-100;
c2.fillStyle = '#696969';
c2.beginPath();
c2.moveTo(centerX, centerY);
c2.lineTo(centerX+200,centerY);
c2.lineTo(centerX+200, centerY+200);
c2.lineTo(centerX, centerY+200);
c2.closePath();
c2.fill();
// adding source location
var ctx = canvas.getContext("2d");
ctx.fillStyle = '#008000';
ctx.beginPath();
ctx.arc( 20, canvas.height-20, 10, 0, 2 * Math.PI);
ctx.stroke();
ctx.closePath();
ctx.fill();
// adding destination location
var ctx1 = canvas.getContext("2d");
ctx1.fillStyle = '#f00';
ctx1.beginPath();
ctx1.arc( canvas.width-20, 20, 10, 0, 2 * Math.PI);
ctx1.stroke();
ctx1.closePath();
ctx1.fill();
}
<!DOCTYPE html>
<html>
<head>
<title>Robot Path Planning</title>
<style>
body {
padding: 0;
margin: 0;
}
</style>
<script src="../p5.min.js"></script>
<script src="../addons/p5.dom.min.js"></script>
<script src="../addons/p5.sound.min.js"></script>
<script src="sketch.js"></script>
</head>
<body>
</body>
</html>
Browser
Memory consumption
Apparently your code is creating a new canvas entity for each draw call and this doesn't make sense.
You should instead create the canvas only once and then just do drawing on it in the draw call. If you need to clear the previous frame you can just reset the width/height properties or call clearRect.

draw a circle over a image in html5 and javascript

html code :
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function start() {
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var image = new Image();
image.onload = function () {
ctx.drawImage(image, 69, 50);
//draw a circle
ctx.beginPath();
ctx.arc(100, 75, 10, 0, Math.PI * 2, true);
ctx.stroke();
};
image.src = 'xy-coordinates.jpg';
}
</script>
</head>
<img id="myImgId" alt="" src="xy-coordinates.jpg" />
<input type="button" value="submit" onclick="start()">
<canvas id="myCanvas" width="700" height="393"></canvas>
</body>
</html>
I'm trying to draw a circle on an image dynamically once I click the button.
The problem is after clicking the button, I'm getting an extra image (with the circle drawn) displayed on the screen rather drawing on original image.
My requirement is to draw a circle on an image which is already displayed.
UPDATED
<script>
function Draw(){
var img = document.getElementById("theImg");
var cnvs = document.getElementById("myCanvas");
cnvs.style.position = "absolute";
cnvs.style.left = img.offsetLeft + "px";
cnvs.style.top = img.offsetTop + "px";
var ctx = cnvs.getContext("2d");
ctx.beginPath();
ctx.arc(250, 210, 10, 0, 2 * Math.PI, false);
ctx.lineWidth = 3;
ctx.stroke();
}
</script>
<img id='theImg' src='xy-coordinates.jpg'>
<input type='button' value='Draw' onclick='draw()' ><br>
<canvas id='myCanvas' width="700" height="393"></canvas>
when < br > is used in html tag befor or after canvas there comes a huge distance betweein image and button r any tags i place in there. how to rectify it ?
You don't need to create one more image because canvas in fact is an image by itself. Place your canvas on top of the source image by setting its position to absolute, left and top same as the source image:
var img = document.getElementById("myImgId");
var c = document.getElementById("myCanvas");
c.style.position = "absolute";
c.style.left = img.offsetLeft;
c.style.top = img.offsetTop;
Then just draw into canvas:
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(100, 75, 10, 0, Math.PI * 2, true);
ctx.stroke();
UPDATE:
function Draw(){
var img = document.getElementById("theImg");
var cnvs = document.getElementById("myCanvas");
cnvs.style.position = "absolute";
cnvs.style.left = img.offsetLeft + "px";
cnvs.style.top = img.offsetTop + "px";
var ctx = cnvs.getContext("2d");
ctx.beginPath();
ctx.arc(250, 210, 200, 0, 2 * Math.PI, false);
ctx.lineWidth = 3;
ctx.strokeStyle = '#00ff00';
ctx.stroke();
}
#draw-btn {
font-size: 14px;
padding: 2px 16px 3px 16px;
margin-bottom: 8px;
}
<div>
<input id='draw-btn' type='button' value='Draw' onclick='Draw()' />
</div>
<img id='theImg' src='http://i.telegraph.co.uk/multimedia/archive/02351/cross-eyed-cat_2351472k.jpg'>
<canvas id='myCanvas' width='536px' height='536px'></canvas>
You are drawing one image on canvas, and second image with "img" tag (already displayed). you can't draw circle with canvas, on HTML tag.

My Line Color is overlapping. What to do?

I'm following the JS tutorial in W3schools and make some improve for the code.
Now My code is as follows:
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="600" height="600"></canvas>
<script>
function getAngle(x, y, angle, h) {
var radians = angle * (Math.PI / 180);
return { x: x + h * Math.cos(radians), y: y + h * Math.sin(radians) };
}
var canvas = document.getElementById('myCanvas');
var lineWidth = 250;
var centerx = canvas.width/2;
var centery = canvas.height/2;
var axisx = canvas.getContext('2d');
var axisy = canvas.getContext('2d');
var L1 = canvas.getContext('2d');
var L2 = canvas.getContext('2d');
var L3 = canvas.getContext('2d');
axisy.beginPath();
axisy.moveTo(centerx, 10);
axisy.lineTo(centerx, 590);
axisy.strokeStyle = '#000000';
axisy.stroke();
axisx.beginPath();
axisx.moveTo(10, centery);
axisx.lineTo(590, centery);
axisx.strokeStyle = '#000000';
axisx.stroke();
L1pos = getAngle(centerx, centery, 25, lineWidth);
L1.moveTo(centerx, centery);
L1.lineTo(L1pos.x, L1pos.y);
L1.strokeStyle = '#ff0000';
L1.stroke();
L2pos = getAngle(centerx, centery, 125, lineWidth);
L2.moveTo(centerx, centery);
L2.lineTo(L2pos.x, L2pos.y);
L2.strokeStyle = '#00ff00';
L2.stroke();
L3pos = getAngle(centerx, centery, 225, lineWidth);
L3.moveTo(centerx, centery);
L3.lineTo(L3pos.x, L3pos.y);
L3.strokeStyle = '#0000ff';
L3.stroke();
</script>
</body>
The result show that all 3 diagonals line (L1, L2, L3) were blue coloured (#0000ff). How to put different color on each line?
Before beginning to draw, you have to call beginPath, to flush the previous line. (see beginPath on w3schools)
L1.beginPath()
see the fiddle: http://jsfiddle.net/UX4gC/

Categories