How to create a (moving) clip mask with trails on a canvas - javascript

I succeed in coding a moving (visible) path with trails – as in
https://www.kirupa.com/canvas/follow_mouse_cursor.htm
But when I replace ctx.fill() with ctx.clip() nothing is seen … Here is my javascript code – see the complete code at https://codepen.io/j-raff/pen/JQxOPj
var jrCanvas = document.getElementById("jr-canvas");
var ctx = jrCanvas.getContext("2d");
var mouseX, mouseY;
var bgImageOnCanvas = new Image();
bgImageOnCanvas.src =
"http://www.graffik.de/wp-content/uploads/forgethers-abgesang-01.png";
bgImageOnCanvas.onload = function() {
ctx.drawImage(bgImageOnCanvas, 0, 0);
};
jrCanvas.addEventListener("mousemove", function(e){
mouseX = e.clientX;
mouseY = e.clientY;
}, false);
function update() {
ctx.save();
ctx.beginPath();
ctx.arc(mouseX, mouseY, 50, 0, Math.PI * 2, true);
ctx.clip();
requestAnimationFrame(update);
}
update();

I solved this in the meantime :)
Had to move the background image into update()
Added ctx.restore() in update()
See https://codepen.io/j-raff/pen/zVepOK
var jrCanvas = document.getElementById("jr-canvas");
var ctx = jrCanvas.getContext("2d");
var mouseX, mouseY;
var x, y;
var bgImageOnCanvas = new Image();
bgImageOnCanvas.src =
"http://www.graffik.de/wp-content/uploads/forgethers-abgesang-01.png";
jrCanvas.addEventListener("mousemove", function(e){
mouseX = e.clientX;
mouseY = e.clientY;
update();
}, false);
function update() {
ctx.save();
ctx.beginPath();
ctx.arc(mouseX, mouseY, 50, 0, Math.PI * 2, true);
ctx.clip();
ctx.drawImage(bgImageOnCanvas, 0, 0);
ctx.restore();
}

Related

Line drawing in canvas with gradient

I'm looking for a solution to freehand draw a line with a gradient in canvas like this:
I already found this, but the gradient seems to be 'locked' on the background and is not following the line.
window.addEventListener('load', ()=>{
resize(); // Resizes the canvas once the window loads
document.addEventListener('mousedown', startPainting);
document.addEventListener('mouseup', stopPainting);
document.addEventListener('mousemove', sketch);
window.addEventListener('resize', resize);
});
const canvas = document.querySelector('#canvas');
const ctx = canvas.getContext('2d');
function resize(){
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
}
let coord = {x:0 , y:0};
let paint = false;
function getPosition(event){
coord.x = event.clientX - canvas.offsetLeft;
coord.y = event.clientY - canvas.offsetTop;
}
function startPainting(event){
paint = true;
getPosition(event);
}
function stopPainting(){
paint = false;
}
function sketch(event){
if (!paint) return;
ctx.beginPath();
ctx.lineWidth = 5;
ctx.lineCap = 'round';
var gradient = ctx.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0.00, 'grey');
gradient.addColorStop(1 / 2, 'white');
gradient.addColorStop(1.00, 'grey');
ctx.strokeStyle = gradient;
ctx.moveTo(coord.x, coord.y);
getPosition(event);
ctx.lineTo(coord.x , coord.y);
ctx.stroke();
}
Can somebody help me please?
I found a way to do it:
var context = canvas.getContext("2d");
context.strokeStyle = '#000000';
context.fillStyle = '#000000';
context.beginPath();
context.moveTo(10, 10);
context.lineTo(50, 10);
context.lineWidth = 2;
context.stroke();
context.beginPath();
context.lineWidth = 15;
context.moveTo(10, 30);
context.lineTo(50, 30);
context.stroke();
context.beginPath();
context.moveTo(10, 50);
context.lineTo(50, 50);
context.lineWidth = 2;
context.stroke();
Where I reconstructed the gradient with multiple lines and a blur on those lines.

How to add gradient effect in selected image object from HTML canvas using jquery

I have html canvas where i dropped image on it i want to apply linear gradient effect on image. My scenario is that user can select some portion of image on canvas by mouse and he can select color from color picker. I want to apply effect on selected portion only.
That sounds like a job for createRadialGradient():
var mouse = {
down: false,
x1: null,
y1: null,
x2: null,
y1: null
};
var grad = 'transparent';
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = init;
img.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/a/a1/D%C3%BClmen%2C_Kirchspiel%2C_B%C3%B6rnste%2C_Feld_--_2017_--_3171.jpg/500px-D%C3%BClmen%2C_Kirchspiel%2C_B%C3%B6rnste%2C_Feld_--_2017_--_3171.jpg";
function updateGrad() {
var cx = mouse.x1;
var cy = mouse.y1;
var dist = Math.hypot(mouse.x1-mouse.x2, mouse.y1-mouse.y2);
grad = ctx.createRadialGradient(cx, cy, 0, cx, cy, dist);
grad.addColorStop(1, 'black');
grad.addColorStop(0, 'transparent');
}
function draw() {
// draw the image
ctx.drawImage(img, 0,0);
// draw the gradient
ctx.fillStyle = grad;
ctx.fillRect(0,0,canvas.width,canvas.height);
// draw the line?
ctx.beginPath();
ctx.rect(mouse.x1 - 4, mouse.y1 - 4, 8, 8);
ctx.moveTo(mouse.x1, mouse.y1);
ctx.lineTo(mouse.x2, mouse.y2);
ctx.rect(mouse.x2 - 4, mouse.y2 - 4, 8, 8);
ctx.stroke();
}
function init() {
canvas.width = this.width;
canvas.height = this.height;
canvas.onmousedown = mousedown;
document.onmousemove = mousemove;
document.onmouseup = mouseup;
ctx.strokeStyle = 'white';
draw();
}
function mousedown(evt) {
var rect = canvas.getBoundingClientRect();
mouse.down = true;
mouse.x1 = evt.clientX - rect.left;
mouse.y1 = evt.clientY - rect.top;
}
function mousemove(evt) {
if(!mouse.down) return;
var rect = canvas.getBoundingClientRect();
mouse.x2 = evt.clientX - rect.left;
mouse.y2 = evt.clientY - rect.top;
updateGrad();
draw();
}
function mouseup(evt) {
mouse.down = false;
}
<canvas id="canvas"></canvas>

Click on object to do certain function

I'm programming on JavaScript and basically what I'm supposed to do is to draw a face on a canvas and those faces have certain effects.
One of the effects I'm supposed to do is to click on the nose and it will change the face to an angry face. I have created objects for all the face parts (nose, eyes, etc.) and what I'm trying to do is that I want the function "angryFace" to be called when the nose is clicked. The nose is already an object.
Been stuck for a long time on this. Would appreciate it if someone could help! Uploaded the whole code down here. Thanks guys!
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>COM1008 Assignment 2</title>
<link rel="stylesheet" href="main1.css">
</head>
<main>
<h1>COM 1008 Assignment 2</h1>
<p>By Samuel Fung Chi Lun</p>
</main>
<body>
<canvas id="canvasFrame" width="600" height="600"></canvas>
<p>
<button name="sadbutton" id="sadFace">Sad</button>
<button name="angrybutton" id="angryFace">Angry</button>
<button name="surprisedbutton" id="surprisedFace">Surprised</button>
<button name="neutralbutton" id="neutralFace">Neutral</button>
</p>
<script>
var canvas = document.getElementById('canvasFrame');
var context = canvas.getContext('2d');
//Function to obtain x and y coordinates of mouse positions - Obtained from 20/11/2017 lecture slides
function getMouseXY(e) {
var boundingRect = canvas.getBoundingClientRect();
var offsetX = boundingRect.left;
var offsetY = boundingRect.top;
var w = (boundingRect.width - canvas.width);
var h = (boundingRect.height - canvas.height);
offsetX += w;
offsetY += h;
var mx = Math.round(e.clientX - offsetX);
var my = Math.round(e.clientY - offsetY);
return { x: mx, y: my };
}
const BROWS_UP = 190;
const BROWS_DOWN = 170;
//Creating an object for left eye brow
var leftEyeB = {
draw: function (x1,brows_direction1,x2,brows_direction2) {
context.beginPath();
context.lineWidth = 18;
context.moveTo(x1, brows_direction1);
context.lineTo(x2, brows_direction2)
context.stroke();
}
};
//Creating an object for right eye brow
var rightEyeB = {
draw: function (x1,brows_direction1,x2,brows_direction2) {
context.beginPath();
context.lineWidth = 18;
context.moveTo(x1, brows_direction1);
context.lineTo(x2, brows_direction2)
context.stroke();
}
};
//Creating an object for the head
var faceShape = {
draw: function() {
context.beginPath();
context.fillStyle = "rgb(255,255,0)"
context.lineWidth = 3;
context.arc(300, 300, 200, 0, Math.PI * 2, true);
context.fill();
context.stroke();
}
}
//Creating an object for the eyes
var eyes = {
draw: function() {
context.beginPath();
context.fillStyle = "rgb(0,0,0)";
context.moveTo(255, 250); //LeftEye
context.arc(220, 250, 40, 0, Math.PI * 2, true);
context.moveTo(415, 250);//Right Eye
context.arc(380, 250, 40, 0, Math.PI * 2, true);
context.fill();
context.fill();
context.stroke();
context.beginPath();
context.fillStyle = "rgb(255,255,255)";
context.moveTo(240, 250); //LeftPupil
context.arc(220, 250, 15, 0, Math.PI * 2, true);
context.moveTo(400, 250); //Right Pupil
context.arc(380, 250, 15, 0, Math.PI * 2, true);
context.fill();
context.stroke();
}
}
//Creating an object for the nose
var nose = {
draw: function() {
context.beginPath();
context.fillStyle = "rgb(0,0,0)";
context.moveTo(300, 275);
context.lineTo(275, 325);
context.lineTo(325, 325);
context.fill();
context.closePath();
context.stroke();
}
}
//Creating an object for the mouth
var mouth = {
frown: function() {
context.beginPath();
context.fillStyle = "rgb(0,0,0)";
context.moveTo(305, 427);//Mouth
context.arc(305, 427, 80, 0, Math.PI, true);
context.fill();
context.closePath();
context.stroke();
},
circle: function() {
context.beginPath();
context.fillStyle = "rgb(0,0,0)";
context.arc(300, 400, 50, 0, Math.PI * 2, true);
context.fill();
context.stroke();
},
straight: function() {
context.beginPath();
context.fillStyle = "rgb(0,0,0)";
context.rect(225, 390, 150, 20);//Mouth
context.fill();
context.stroke();
}
}
//Drawing the sad face
function sadFace() {
faceShape.draw();
eyes.draw();
nose.draw();
mouth.frown();
leftEyeB.draw(175,BROWS_DOWN,265,BROWS_DOWN);
rightEyeB.draw(335,BROWS_DOWN,425,BROWS_DOWN);
}
//Drawing the angry face
function angryFace() {
faceShape.draw();
eyes.draw();
nose.draw();
mouth.frown();
leftEyeB.draw(175,BROWS_DOWN,265,BROWS_UP);
rightEyeB.draw(335,BROWS_UP,425,BROWS_DOWN);
}
//Drawing the surprised face
function surprisedFace() {
faceShape.draw();
eyes.draw();
nose.draw();
mouth.circle();
leftEyeB.draw(175,BROWS_UP,265,BROWS_DOWN);
rightEyeB.draw(335,BROWS_DOWN,425,BROWS_UP);
}
//Drawing the neutral face
function neutralFace() {
faceShape.draw();
eyes.draw();
nose.draw();
mouth.circle();
leftEyeB.draw(175,BROWS_DOWN,265,BROWS_DOWN);
rightEyeB.draw(335,BROWS_DOWN,425,BROWS_DOWN);
}
//Not sure how to properly do the bottom part. It does not work at all for the eyebrows one so please help!
function effects() {
//Click on the eyebrows to raise them
if (mousePosition.x > x1 && mousePosition.x < x2 && mousePosition.y < BROWS_UP && mousePosition.y > BROWS_DOWN) {
BROWS_UP += 20;
}
//Click on eye to show angry face
if (mousePosition = on coordinates of the eye) {
angryFace();
}
//Click on nose to show happy face
if (mousePosition = on coordinates of the nose) {
smileFace();
}
}
canvas.addEventListener('click', function(evt) {
effects(evt);
});
neutralFace();
//Linking the face functions to the buttons
var angryButton = document.getElementById("angryFace");
var sadButton = document.getElementById("sadFace");
var surprisedButton = document.getElementById("surprisedFace");
var neutralButton = document.getElementById("neutralFace");
sadButton.addEventListener("click", sadFace);
angryButton.addEventListener("click", angryFace);
surprisedButton.addEventListener("click", surprisedFace);
neutralButton.addEventListener("click", neutralFace);
</script>
</body>
</html>
When you make face, for you, there are different objects(say nose, eyes etc). For DOM, there is only 1 object i.e. Canvas. So when you click, you are clicking on canvas and not nose.
So to achieve this, you will have to play with coordinates. You have to assume the position of every container and on click of canvas, check the coordinates. If the coordinates are within range of some object, fire necessary function.
canvas.addEventListener('click', function(event){
var x = event.clientX, y = event.clientY;
if(x> 280 && x <335 && y > 280 && y <335) {
// nose is clicked.
angryFace();
}
else {
neutralFace();
}
})
Following is a partial sample:
var canvas = document.getElementById('canvasFrame');
var context = canvas.getContext('2d');
//Function to obtain x and y coordinates of mouse positions - Obtained from 20/11/2017 lecture slides
function getMouseXY(e) {
var boundingRect = canvas.getBoundingClientRect();
var offsetX = boundingRect.left;
var offsetY = boundingRect.top;
var w = (boundingRect.width - canvas.width);
var h = (boundingRect.height - canvas.height);
offsetX += w;
offsetY += h;
var mx = Math.round(e.clientX - offsetX);
var my = Math.round(e.clientY - offsetY);
return {
x: mx,
y: my
};
}
const BROWS_UP = 190;
const BROWS_DOWN = 170;
//Creating an object for left eye brow
var leftEyeB = {
draw: function(x1, brows_direction1, x2, brows_direction2) {
context.beginPath();
context.lineWidth = 18;
context.moveTo(x1, brows_direction1);
context.lineTo(x2, brows_direction2)
context.stroke();
}
};
//Creating an object for right eye brow
var rightEyeB = {
draw: function(x1, brows_direction1, x2, brows_direction2) {
context.beginPath();
context.lineWidth = 18;
context.moveTo(x1, brows_direction1);
context.lineTo(x2, brows_direction2)
context.stroke();
}
};
//Creating an object for the head
var faceShape = {
draw: function() {
context.beginPath();
context.fillStyle = "rgb(255,255,0)"
context.lineWidth = 3;
context.arc(300, 300, 200, 0, Math.PI * 2, true);
context.fill();
context.stroke();
}
}
//Creating an object for the eyes
var eyes = {
draw: function() {
context.beginPath();
context.fillStyle = "rgb(0,0,0)";
context.moveTo(255, 250); //LeftEye
context.arc(220, 250, 40, 0, Math.PI * 2, true);
context.moveTo(415, 250); //Right Eye
context.arc(380, 250, 40, 0, Math.PI * 2, true);
context.fill();
context.fill();
context.stroke();
context.beginPath();
context.fillStyle = "rgb(255,255,255)";
context.moveTo(240, 250); //LeftPupil
context.arc(220, 250, 15, 0, Math.PI * 2, true);
context.moveTo(400, 250); //Right Pupil
context.arc(380, 250, 15, 0, Math.PI * 2, true);
context.fill();
context.stroke();
}
}
//Creating an object for the nose
var nose = {
draw: function() {
context.beginPath();
context.fillStyle = "rgb(0,0,0)";
context.moveTo(300, 275);
context.lineTo(275, 325);
context.lineTo(325, 325);
context.fill();
context.closePath();
context.stroke();
}
}
//Creating an object for the mouth
var mouth = {
frown: function() {
context.beginPath();
context.fillStyle = "rgb(0,0,0)";
context.moveTo(305, 427); //Mouth
context.arc(305, 427, 80, 0, Math.PI, true);
context.fill();
context.closePath();
context.stroke();
},
circle: function() {
context.beginPath();
context.fillStyle = "rgb(0,0,0)";
context.arc(300, 400, 50, 0, Math.PI * 2, true);
context.fill();
context.stroke();
},
straight: function() {
context.beginPath();
context.fillStyle = "rgb(0,0,0)";
context.rect(225, 390, 150, 20); //Mouth
context.fill();
context.stroke();
}
}
//Drawing the sad face
function sadFace() {
faceShape.draw();
eyes.draw();
nose.draw();
mouth.frown();
leftEyeB.draw(175, BROWS_DOWN, 265, BROWS_DOWN);
rightEyeB.draw(335, BROWS_DOWN, 425, BROWS_DOWN);
}
//Drawing the angry face
function angryFace() {
faceShape.draw();
eyes.draw();
nose.draw();
mouth.frown();
leftEyeB.draw(175, BROWS_DOWN, 265, BROWS_UP);
rightEyeB.draw(335, BROWS_UP, 425, BROWS_DOWN);
}
//Drawing the surprised face
function surprisedFace() {
faceShape.draw();
eyes.draw();
nose.draw();
mouth.circle();
leftEyeB.draw(175, BROWS_UP, 265, BROWS_DOWN);
rightEyeB.draw(335, BROWS_DOWN, 425, BROWS_UP);
}
//Drawing the neutral face
function neutralFace() {
faceShape.draw();
eyes.draw();
nose.draw();
mouth.circle();
leftEyeB.draw(175, BROWS_DOWN, 265, BROWS_DOWN);
rightEyeB.draw(335, BROWS_DOWN, 425, BROWS_DOWN);
}
function effects() {
mousePosition = getMouseXY(e);
console.log(mousePosition);
}
neutralFace();
canvas.addEventListener('click', function(event){
var x = event.clientX, y = event.clientY;
if(x> 280 && x <335 && y > 280 && y <335) {
// nose is clicked.
angryFace();
}
else {
neutralFace();
}
})
//Linking the face functions to the buttons
var angryButton = document.getElementById("angryFace");
var sadButton = document.getElementById("sadFace");
var surprisedButton = document.getElementById("surprisedFace");
var neutralButton = document.getElementById("neutralFace");
sadButton.addEventListener("click", sadFace);
angryButton.addEventListener("click", angryFace);
surprisedButton.addEventListener("click", surprisedFace);
neutralButton.addEventListener("click", neutralFace);
<!-- This is not the original markup. This is a part of an edit to make the code executable. -->
<canvas id='canvasFrame' width=600 height=600></canvas>
<div>
<button id="angryFace">Angry Face</button>
<button id="sadFace">Sad Face</button>
<button id="surprisedFace">Surprised Face</button>
<button id="neutralFace">Neutral Face</button>
</div>

How to fade out an item in canvas

I have a full screen canvas in my page. There are also some dive elements over this canvas. there is an circle element in the canvas that moves with the cursor everywhere in the page. However when the cursor arrives to the div element over the canvas, the circle shape stays in the last place it was on the canvas before arriving to the div.
DEMO: JSFIDDLE
Is ther any way that I can fade-out the circle shape when the cursor is over the div element and fade it in when it backs to the canvas?
Also is there any other effect rather than fading out? like making it small and then fade-out...
Here is the bit of code related to the circle:
function writeMessage(canvas, message, x, y) {
var context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
var pattern = context.createPattern(imageResized, 'no-repeat');//Use imageResized, not imageObj.
context.fillStyle = pattern;
context.fill();
context.fillStyle = 'black';
context.beginPath();
context.arc(x, y, 60, 0, 2 * Math.PI);
}
Well, you can always create your own fade function that gets called on mouseout (or mouseleave) event. Here's one I quickly built for you:
function fadeOut(canvas, message, x, y, amount) {
var context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
var pattern = context.createPattern(imageResized, 'no-repeat');
context.fillStyle = pattern;
context.fill();
context.font = '28pt Calibri';
context.fillStyle = 'black';
context.beginPath();
context.arc(x, y, amount, 0, 2 * Math.PI);
if (amount > 0) {
setTimeout(function(){
fadeOut(canvas, message, x, y, --amount);
}, 2);
}
else {
context.clearRect(0, 0, canvas.width, canvas.height);
}
}
See it in action here: http://jsfiddle.net/2p9dn8ed/42/
Or in the snippet:
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var x = 0;
var y = 0;
var width = window.innerWidth;
var height = window.innerHeight;
var imageObj = new Image();
console.log(window.innerWidth + "----" + window.innerHeight);
//Create another canvas to darw a resized image to.
var imageResized = document.createElement('canvas');
imageResized.width = width;
imageResized.height = height;
//Wait for the original image to low to draw the resize.
imageObj.onload = function() {
//Find hoe mauch to scale the image up to cover.
var scaleX = width / imageObj.width;
var scaleY = height / imageObj.height;
var scaleMax = Math.max(scaleX, scaleY);
var ctx = imageResized.getContext('2d');
ctx.scale(scaleMax, scaleMax);
ctx.drawImage(imageObj, 0, 0);
};
imageObj.src = 'http://www.html5canvastutorials.com/demos/assets/darth-vader.jpg';
function writeMessage(canvas, message, x, y) {
var context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
var pattern = context.createPattern(imageResized, 'no-repeat');//Use imageResized, not imageObj.
context.fillStyle = pattern;
context.fill();
context.font = '28pt Calibri';
context.fillStyle = 'black';
//context.fillText(message, x, y);
context.beginPath();
context.arc(x, y, 60, 0, 2 * Math.PI);
//context.stroke();
//
}
function fadeOut(canvas, message, x, y, amount) {
var context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
var pattern = context.createPattern(imageResized, 'no-repeat');//Use imageResized, not imageObj.
context.fillStyle = pattern;
context.fill();
context.font = '28pt Calibri';
context.fillStyle = 'black';
//context.fillText(message, x, y);
context.beginPath();
context.arc(x, y, amount, 0, 2 * Math.PI);
//context.stroke();
//
if (amount > 0) {
setTimeout(function(){
fadeOut(canvas, message, x, y, --amount);
}, 2);
}
else {
context.clearRect(0, 0, canvas.width, canvas.height);
}
}
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
canvas.addEventListener('mousemove', function (evt) {
var mousePos = getMousePos(canvas, evt);
var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
writeMessage(canvas, message, mousePos.x, mousePos.y);
}, false);
canvas.addEventListener('mouseout', function(evt){
var mousePos = getMousePos(canvas, evt);
var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
console.log(1);
fadeOut(canvas, message, mousePos.x, mousePos.y, 60);
});
// Get the canvas element form the page
var canvas = document.getElementById("myCanvas");
/* Rresize the canvas to occupy the full page,
by getting the widow width and height and setting it to canvas*/
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
anvas, img {
display:block;
margin:1em auto;
border:1px solid black;
}
canvas {
background:url('../img/spiral_galaxy-1920x1080.jpg');
background-size: cover;
position: absolute;
left: 0; top: 0;
width: 100%; height: 100%;
z-index:-1;
}
div{
width:200px;
height:200px;
background:rgba(0,0,0,0.5);
position: fixed;
top: 20%;
left: 20%;
}
<canvas id="myCanvas" width="578" height="400"></canvas>
<div><h1>TEXT</h1></div>

Mask image in html canvas

Im trying to change a mask to an image in a html5 canvas when the mouse enters the canvas.
When the mouse enters the canvas i draw a shape thats gonna act as a mask. It draws as i want but it wont mask the image.
The function that draws the mask is drawLine();
What is wrong here?
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var img = document.createElement('IMG');
var mY;
var mX;
img.onload = function () {
context.save();
context.beginPath();
context.moveTo(0, 0);
context.lineTo(160, 600);
context.rect(0, 0, 160, 600);
context.closePath();
context.clip();
context.drawImage(img, 0, 0);
context.restore();
};
img.src = "http://placekitten.com/160/600";
canvas.addEventListener('mouseenter', function(evt) {
var mousePos = getMousePos(canvas, evt);
var message = mousePos.y + ', ' + mousePos.x;
mY = mousePos.y;
mX = mousePos.x;
drawLine();
}, false);
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
function drawLine() {
if(mX > 80) {
context.restore();
context.fillStyle = "rgb(000,000,000)";
context.beginPath();
context.moveTo(160, mY);
context.lineTo(0,mY+setCutAngle());
context.lineTo(0,600);
context.lineTo(160,600);
context.fill();
context.closePath();
} else {
}
context.stroke();
}
function setCutAngle() {
return Math.floor(Math.random() * 45) + 10;
}
Is this what you are looking for? JSFIDDLE Updated so image loads at the start.
I believe your main problem was caused by not clearing the canvas. Thus your clip would not show
Updated JSFIDDLE to match your code. Remove that logic from your load event. It should only happen on your drawevent. You are also not clearling or clipping your image in the draw event.
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var img = document.createElement('IMG');
var mY;
var mX;
img.onload = function () {
context.drawImage(img, 0, 0);
};
img.src = "http://placekitten.com/160/600";
canvas.addEventListener('mouseenter', function(evt) {
var mousePos = getMousePos(canvas, evt);
var message = mousePos.y + ', ' + mousePos.x;
mY = mousePos.y;
mX = mousePos.x;
drawLine();
}, false);
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
function drawLine() {
context.save();
context.clearRect(0, 0, canvas.width, canvas.height);
if(mX > 80) {
context.restore();
context.fillStyle = "rgb(000,000,000)";
context.beginPath();
context.moveTo(160, mY);
context.lineTo(0,mY+setCutAngle());
context.lineTo(0,600);
context.lineTo(160,600);
context.clip();
context.drawImage(img, 0, 0);
context.closePath();
} else {
}
context.stroke()
}
function setCutAngle() {
return Math.floor(Math.random() * 45) + 10;
}

Categories