Need to crop canvas and not resize it using jquery - javascript

I'm actually working on a project which overlay two image, with one that the user upload it and the second is by default.
My only problem is when the uploaded image is a rectangle and not a square, the canvas is resizing it. I need that the canvas crop my image, and be a square. Then I can apply the filter.
Here is my code:
$('.file1, .file2').on('change', function() {
var reader = new FileReader(),
imageSelector = $(this).data('image-selector');
if (this.files && this.files[0]) {
reader.onload = function(e) {
imageIsLoaded(e, imageSelector)
};
reader.readAsDataURL(this.files[0]);
}
});
$('.btn-merge').on('click', merge);
function imageIsLoaded(e, imageSelector) {
$(imageSelector).attr('src', e.target.result);
$(imageSelector).removeClass('hidden');
};
function merge() {
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d'),
imageObj1 = new Image(),
imageObj2 = new Image();
canvas.width = 300;
canvas.height = 300;
imageObj1.src = $('.image1').attr('src');
imageObj1.onload = function() {
ctx.globalAlpha = 1;
ctx.drawImage(imageObj1, 0, 0, 300, 300);
imageObj2.src = $('.image2').attr('src');
imageObj2.onload = function() {
ctx.globalAlpha = 1;
ctx.drawImage(imageObj2, 0, 0, 300, 300);
var img = canvas.toDataURL('img/png');
$('.merged-image').attr('src', img);
var mergedimage = document.getElementById('mergedimage');
$('.merged-image').removeClass('hidden');
$("#downloadfinal").attr("href", mergedimage.src);
}
};
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<div class="container-fluid shadow">
<div class="container d-flex flex-column justify-content-center">
<div class="row mb-1 ">
<h2>Votre photo ici : </h2>
<label class="custom ml-3 hover-underline-animation"> <input class="ml-2 file1" type="file" data-image-selector=".image1" />Selectionner un fichier</label>
</div>
<img class="image1 hidden mb-4" alt="abs" width="200px" height="auto" />
<div class="row">
<h2 class="mr-2 ">Filtre par défaut : </h2>
<img alt="abs image3" width="200px" height="auto" src="img/filtre.png" />
</div>
<div class="otherfilter">
<div class="row mt-5 mb-5">
<h2 class="">Mettez un autre filtre ici : </h2>
<label class="custom ml-3 hover-underline-animation"> <input class="ml-2 file2" type="file" data-image-selector=".image2" />Selectionner un fichier</label>
</div>
<img class="hidden image2" alt="ab" width="200px" height="auto" src="img/filtre.png">
</div>
</div>
<br />
<div class="text-center mb-5">
<input class="btn-merge mb-3" type="button" value="Appliquer le filtre" />
<br />
<img class="merged-image hidden mb-3" id="mergedimage" alt="merged image" />
<canvas id="canvas" class="hidden"></canvas>
<br>
<a class="btn-dl" id="downloadfinal" role="button" href="#" download="photo_profil_modifie">
<i class="mr-2 bi bi-download"></i>Télécharger
</a>
</div>
Thanks for read this, hope my english is good, if you don't understand tell me.

To do this you need to scale the input image to fit the canvas either horizontally or vertically while maintaining it's aspect ratio.
That's not hard to do as things are a bit easier since the canvas is squarish. Say we have a canvas of 300 x 300 pixel and we want to draw a non-square image of 400 x 300 onto. First we take the width or height of the canvas - it does not really matter as it's the same - and divide it by the bigger side of the image - 400 in this case.
300 / 400 == 0.75
This is the scale we need to multiply both the width and height of the image before drawing it onto the canvas.
Here's an example:
let canvas = document.getElementById('canvas');
let context = canvas.getContext('2d');
let imageObj1 = new Image();
imageObj1.crossOrigin = 'anonymous';
imageObj1.crossOrigin = 'anonymous';
imageObj1.onload = () => {
let scale = imageObj1.width > imageObj1.height ? canvas.width / imageObj1.width : canvas.height / imageObj1.height;
context.drawImage(imageObj1, canvas.width / 2 - imageObj1.width * scale / 2, canvas.height / 2 - imageObj1.height * scale / 2, imageObj1.width * scale, imageObj1.height * scale);
}
imageObj1.src = 'https://api.codetabs.com/v1/proxy?quest=https://picsum.photos/id/237/300/400';
#canvas {
background: blue;
}
<canvas id="canvas" width="300" height="300"></canvas>
If you prefer to not have unused area on your canvas and stretch the image to the whole canvas and crop the exceess, you simply divide the smaller side of your image by the canvas width/height.
For example:
//ctx.drawImage(imageObj1, 0, 0, 300, 300);let image = new Image();
let canvas = document.getElementById('canvas');
let context = canvas.getContext('2d');
let imageObj1 = new Image();
imageObj1.crossOrigin = 'anonymous';
imageObj1.crossOrigin = 'anonymous';
imageObj1.onload = () => {
let scale = imageObj1.width < imageObj1.height ? canvas.width / imageObj1.width : canvas.height / imageObj1.height;
context.drawImage(imageObj1, canvas.width / 2 - imageObj1.width * scale / 2, canvas.height / 2 - imageObj1.height * scale / 2, imageObj1.width * scale, imageObj1.height * scale);
}
imageObj1.src = 'https://api.codetabs.com/v1/proxy?quest=https://picsum.photos/id/237/300/400';
<canvas id="canvas" width="300" height="300"></canvas>

Related

How do I add a download button that will download the image after making changes?

I am working on a photo editor and I want to add a download button that will download the image after the user makes the necessary changes. The changes are working fine but I am not able to figure out how to download the image (Please keep in mind that the filter value depends on the user and is not constant). Does anyone have any ideas on how I can proceed further?
(P.S. I searched all over Stack Overflow and tried to implement every solution in my code but nothing's working)
Here's my HTML:
<!-- upload image button -->
<p><input type="file" accept="image/*" name="image" id="file" onchange="loadFile(event)" style="display: none;"></p>
<p><label for="file" style="cursor: pointer;" id="fileBtn">UPLOAD IMAGE</label></p>
<p><img id="img"></p>
<!-- side nav -->
<div class="sidenav">
<label for="filter-select">FILTER AND ADJUST</label>
<div class="slider">
<p style="color: aliceblue;">Sepia</p>
<input id="sepia" type="range" oninput="setSepia(this);" value="0" step="0.1" min="0" max="1"><span id="Amount" style="color: white;"> 0</span><br/><br>
<p style="color: aliceblue;">Grayscale</p>
<input id="Grayscale" type="range" oninput="setGs(this);" value="0" step="0.1" min="0" max="1"><span id="Amount2" style="color: white;"> 0</span><br/><br>
</div>
<label onclick = "RotateImg()">ROTATE</label>
<label onclick = "flipping()">FLIP</label>
<label onclick = "invert()">INVERT COLOURS</label>
<label onclick = "original()">ORIGINAL</label>
</div>
Here's my JavaScript:
function loadFile(event) {
var image = document.getElementById('img');
image.src = URL.createObjectURL(event.target.files[0]);
}
const options = {
sepia: 0,
grayscale: 0,
rotation: 0,
scale: 1,
invertVal: 0
};
function setSepia(e){
options.sepia = e.value;
document.getElementById('Amount').innerHTML= e.value;
redraw();
}
function setGs(e){
options.grayscale = e.value;
document.getElementById('Amount2').innerHTML= e.value;
redraw();
}
let rotation = 0;
function RotateImg(){
rotation += 90;
if (rotation == 360) {
rotation = 0;
}
options.rotation = rotation;
redraw();
}
let scale = 1
function flipping() {
scale -= 2
if (scale <= -2) {
scale = 1;
}
options.scale = scale;
redraw();
}
let invertVal = 0
function invert() {
invertVal += 100
if (invertVal > 100) {
invertVal = 0
}
options.invertVal = invertVal;
redraw();
}
function original() {
document.getElementById("img").style["webkitFilter"] ="sepia(0) grayscale(0)";
document.querySelector("img").style.transform = "rotate(0deg) scaleX(1)";
}
function redraw() {
document.getElementById("img").style["webkitFilter"] ="sepia(" + options.sepia + ") grayscale(" + options.grayscale + ");
document.querySelector("img").style.transform = `rotate(${options.rotation}deg) scaleX(${options.scale})`;
}
Your best bet would be to use the Canvas API to apply your edits and then use toDataURL to set up the download.
Here's a proof of concept fiddle:
<div id="container">
<img src="//placekitten.com/400/400" crossorigin="anonymous"/>
<canvas width="400" height="400" />
</div>
const canvas = document.querySelector('canvas');
const image = document.querySelector('img');
image.addEventListener('load', () => {
const ctx = canvas.getContext('2d');
// draw the image into the canvas with a sepia filter:
ctx.filter = 'sepia(1)';
ctx.drawImage(image, 0, 0);
// set up the download link
addDownload(canvas);
})
function addDownload (canvas) {
// create an <a>
const a = document.createElement('a');
// set it up to download instead of navigating
a.setAttribute('download', 'kitten.jpg');
a.innerHTML = "download";
// set the href to a data url for the image
a.href = canvas.toDataURL('image/jpg');
// append it to the dom
container.appendChild(a);
}

How to draw in more than two canvases HTML & JS

I'm working on a proyect and i need to draw in almost 5 canvas. I've created the first canvas successfully but when i put in the code the second i only can draw on this latest canvas.
I read than the problem can be the context("2d") i tryed to separate saving in a different ctx varaible like, ctx2 or things like this.
This is my code:
HTML
<!--First Canvas-->
<div class="col-sm-12 col-lg-6 mt-5 d-flex flex-column justify-content-center">
<div id="contenedor-pizarra-cervical" class="contenedor-pizarra mx-auto">
<canvas id="pizarra-cervical"></canvas>
</div>
</div>
<!--Second Canvas-->
<div class="col-sm-12 col-lg-6 mt-5 d-flex flex-column justify-content-center">
<div id="contenedor-pizarra-postural" class="contenedor-pizarra mx-auto">
<canvas id="pizarra-postural"></canvas>
</div>
</div>
JS OF THE FIRST CANVAS WORKING OK:
//Canvas Cervical
var canvasCervical = document.getElementById("pizarra-cervical");
var ctx = canvasCervical.getContext("2d");
var painting = document.getElementById("contenedor-pizarra-cervical");
var paintStyle = getComputedStyle(painting);
canvasCervical.width = parseInt(paintStyle.getPropertyValue("width"));
canvasCervical.height = parseInt(paintStyle.getPropertyValue("height"));
var mouse = {x: 0, y: 0};
canvasCervical.addEventListener('mousemove', function(e){
mouse.x = e.pageX - this.offsetLeft;
mouse.y = e.pageY - this.offsetTop
}, false);
ctx.lineWidth = 3;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = '#7baeb0';
canvasCervical.addEventListener('mousedown', function(e){
ctx.beginPath();
ctx.moveTo(mouse.x, mouse.y);
canvasCervical.addEventListener('mousemove', onPaint, false);
}, false);
canvasCervical.addEventListener('mouseup', function(){
canvasCervical.removeEventListener('mousemove', onPaint, false)
},false);
var onPaint = function (){
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
};
If you require the same behaviour to happen on multiple canvasses, then you could define the configuration logic in its own function, providing the canvas element as an argument, like this:
let configureCanvas = canvas => {
let painting = canvas.parentNode;
let paintStyle = getComputedStyle(painting);
let mouse = { x: 0, y: 0 };
let onPaint = () => {
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
};
canvas.width = parseInt(paintStyle.getPropertyValue("width"));
canvas.height = parseInt(paintStyle.getPropertyValue("height"));
let ctx = canvas.getContext("2d");
ctx.lineWidth = 3;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = '#7baeb0';
canvas.addEventListener('mousemove', function(e) {
mouse.x = e.pageX - this.offsetLeft;
mouse.y = e.pageY - this.offsetTop
}, false);
canvas.addEventListener('mousedown', function(e) {
ctx.beginPath();
ctx.moveTo(mouse.x, mouse.y);
canvas.addEventListener('mousemove', onPaint, false);
}, false);
canvas.addEventListener('mouseup', function() {
canvas.removeEventListener('mousemove', onPaint, false)
}, false);
canvas.nextElementSibling.addEventListener('click', function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
});
}
configureCanvas(document.getElementById("pizarra-cervical"));
configureCanvas(document.getElementById("pizarra-postural"));
canvas {
border: 1px solid #CCC;
}
<!--First Canvas-->
<div class="col-sm-12 col-lg-6 mt-5 d-flex flex-column justify-content-center">
<div id="contenedor-pizarra-cervical" class="contenedor-pizarra mx-auto">
<canvas id="pizarra-cervical"></canvas>
<button class="clear">Clear</button>
</div>
</div>
<!--Second Canvas-->
<div class="col-sm-12 col-lg-6 mt-5 d-flex flex-column justify-content-center">
<div id="contenedor-pizarra-postural" class="contenedor-pizarra mx-auto">
<canvas id="pizarra-postural"></canvas>
<button class="clear">Clear</button>
</div>
</div>
Taking this a step further, I'd suggest defining your own Class to handle the initialisation, configuration and event handlers of your canvas elements, but that's well outside the remit of this question.

Canvas in Bootstrap modal is giving me wrong mouse coordinates

Im trying to figure out what im dooing wrong. I have a hmtl5 canvas inside a bootstrap modal. The canvas is a selecting game where you select objects inside the canvas and manipulate them.
Unfortunately it works allright in the center of the 600x600px Canvas but im getting a wierd offset when im trying to get the coordinates in the corner of the picture. The offset is getting bigger as you get closer to the corners
Here's my code.
Thank you very much in advance!
Javascript:
document.addEventListener('DOMContentLoaded', (ev) => {
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
canvas.width = 600;
canvas.height = 600;
let imgObj = new Image();
imgObj.onload = function() {
let w = canvas.width;
let nw = imgObj.naturalWidth; //1350
let nh = imgObj.naturalHeight; //900
console.log(nw);
console.log(nh);
let aspect = nw / nh;
let h = w / aspect;
console.log('height', h)
canvas.height = h;
soldTilesDisplay.textContent = totalTiles-soldTiles;
ctx.drawImage(imgObj, 0, 0, w, h);
rectangulize_with_IDs();
fillarraywithrandomTiles(soldTiles);
//greyscaleOriginal();
//ctx.drawImage(imgObj, dx, dy);
//ctx.drawImage(imgObj, dx, dy, dw, dh);
//ctx.drawImage(imgObj, sx, sy, sw, sh, dx, dy, dw, dh);
};
function getMousePosition(canvas, event) {
let rect = canvas.getBoundingClientRect();
let x = event.clientX - Math.floor(rect.left);
let y = event.clientY - Math.floor(rect.top);
storePixelArray(x, y); // originale "Store in Array funktion"
store_rect(x,y);
clickcounter = clickcounter + 1;
console.log("Exact Coordinates: X: " + x,
" Y: " + y, "CLick Counter: "+ clickcounter);
}
Html:
<div>
<!-- Bootstrap Modal here!-->
<div class="row">
<div class="col-lg-4">
<!-- Bootstrap Modal here!-->
<div class="modal fade" id="myModal1">
<div class="modal-dialog modal-xl">
<div class="modal-content">
<div class="modal-header">
<h3>WIN!</h3>
</div>
<div class="modal-body">
<div class="container-fluid">
<div class="row">
<div class="col-md-6">
<canvas id="canvas" style="background-image: url('/images/Berge.png')"></canvas>
</div>
<div class="col-md-6 justify-content-center">
<div class="card text-center" style="width: 30rem;">
<div class="card-body">
<h5 class="card-title" id="Punktestand"> Card Title
Score:
</h5>
<p class="card-text" id="paragraphImModal">With supporting
text below as a natural
lead-in to additional content.</p>
<button type="button" class="btn btn-default" id="usePointsPixelButton">
Select Pixel first</button>
<br>
<h5 class="selectedPixelAmount" id="AmountOfPixels"> </h5>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary btn-lg" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
I found the problem after running into the same Issue.
It is because the class .modal-dialog and every subclass under it has a relative positioning. just set the positioning to unset and you get the correct coordinates.
in my case i had to change following classes:
.modal-dialog {
position: unset;
}
.modal-content {
position: unset;
}
.modal-body {
position: unset;
}
.alert {
position: unset;
}
If you want you can do css stuff like "just change the position of modal-body inside modal dialog" so you dont mess up anything else :)

Could not display the full image draw canvas using HTML and JavaScript

I can not able to draw the full image using canvas. Here is my code:
<div class="form-group">
<label for="exampleInputEmail1">Coupon Title</label>
<input type="text" name="emails" id="copTitle" class="form-control" placeholder="Add Coupon Title" value="<?php echo $email; ?>" required>
</div>
<div class="couponimg" style="display:none;" id="blankImagediv">
<img class="img-responsive thumbnail" style="margin-bottom:9px; display:none;" src="http://oditek.inimages/coupon-banner-blank.jpg" crossorigin="anonymous" id="requiredImage">
<canvas id="canvas" class="img-responsive thumbnail" style="margin-bottom:9px;"></canvas>
</div>
var canvas = document.getElementById('canvas'),
ctx = canvas.getContext('2d');
canvas.width = $('#requiredImage').width();
canvas.crossOrigin = "Anonymous";
canvas.height = $('#requiredImage').height();
ctx.drawImage($('#requiredImage').get(0), 0, 0);
ctx.font = ":26pt Calibri";
$(document).on('input','#copTitle',function(){
$('#blankImagediv').css('display','block');
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.drawImage($('#requiredImage').get(0), 0, 0);
ctx.fillStyle = "#0D5F90";
ctx.fillText($(this).val(),40,80);
})
Here I am getting the half of the image of original image while drawing. The right hand side of the image is not displaying.
hi try with following code...
var canvas = document.getElementById('canvas'),
img = document.getElementById('requiredImage'),
ctx = canvas.getContext('2d');
img.onload = drawImage;
canvas.width = img.width;
canvas.height = img.height;
ctx.font = ":26pt Calibri";
$(document).on('input', '#copTitle', function() {
$('#blankImagediv').css('display', 'block');
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);
ctx.fillStyle = "#0D5F90";
ctx.fillText($(this).val(), 40, 80);
});
function drawImage()
{
ctx.drawImage(img, 0, 0);
}

html5-canvas drawing curve on move of slider

Hi I want to draw a curve as I move slider. I have two kinds of curves. Bezier curve and quadratic cruve. Also As I draw the curve I want to move an object on that same path. I want it to be dynamic so If I should be able to change the curve points.
So I need a function which I can call on the slider change as I am doing for line.
Here is my code. This code will work only in chrome.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style type="text/css">
.wrapper {
margin: 0 auto;
width: 1000px;
}
.canHdr {
float: left;
width: 450px;
height: 400px;
border: 1px solid red;
}
</style>
</head>
<body>
<form>
<!-- wrapper -->
<div class="wrapper">
<!-- canHdr -->
<div id="canHdr" class="canHdr" >
<p>
This is my 1st div with quadratic curve I want to draw this curve as I move the slider. I want to make it dynamic so when I should be able to change the curve points. Also I want to move an object on that curve as I am doing in my 3rd div.
</p>
<div class="canOuterHdr" >
<canvas id="myCanvas1" width="300" height="195" style="position: relative;">
[No canvas support]
</canvas>
</div>
<div id="slider1" class="newBg">
<input id="slide1" type="range" min="0" max="100" step="1" value="0" onchange="counterSlider('slide1');" />
</div>
</div>
<!--/ canHdr -->
<!-- canHdr2 -->
<div id="canHdr2" class="canHdr" >
<p>
This is my 2nd div. I have bezier curve. I want to make it dynamic so when I should be able to change the curve points. Also I want to move an object on that curve as I am doing in my 3rd div.
</p>
<div class="canOuterHdr" >
<canvas id="myCanvas2" width="300" height="195" style="position: relative;">
[No canvas support]
</canvas>
</div>
<div id="slider2" class="newBg">
<input id="slide2" type="range" min="0" max="100" step="1" value="0" onchange="counterSlider('slide2');" />
</div>
</div>
<!-- canHdr2 -->
<!-- canHdr3 -->
<div id="canHdr3" class="canHdr" >
<p>
This is my 3rd div with slanting line. I want to move a ball on this line when I move the slider. So as the line increases ball will also move on the line.
</p>
<div class="canOuterHdr" >
<canvas id="myCanvas3" width="300" height="195" style="position: relative;">
[No canvas support]
</canvas>
</div>
<div id="slider3" class="newBg">
<input id="slide3" type="range" min="0" max="100" step="1" value="0" onchange=" drawSlopeCurve2('slide3','100'); " />
</div>
</div>
<!--/ canHdr3 -->
<!-- canHdr4 -->
<div id="canHdr4" class="canHdr" >
<p>
This is my 4th div with slanting line. I want to move a ball on this line when I move the slider. So as the line increases ball will also move on the line.
</p>
<div class="canOuterHdr" >
<canvas id="myCanvas4" width="300" height="195" style="position: relative;">
[No canvas support]
</canvas>
</div>
<div id="slider4" class="newBg">
<input id="slide4" type="range" min="0" max="100" step="1" value="0" onchange=" drawSlopeCurve1('slide4','100'); " />
</div>
</div>
<!--/ canHdr4 -->
</div>
<!-- /wrapper -->
<script type="text/javascript">
newSprite('myCanvas3', 16, 170);
quadraticCurve('myCanvas1', 18.8, 45, 28, 160, 228, 165);
bezierCurve('myCanvas2', 20, 75, 55.2, 150.0, 200,100, 228, 165)
function counterSlider(sID) {
var slideVal = document.getElementById(sID).value;
/*if (maxValue ==100){
slideVal=slideVal/100;
}*/
slideVal = slideVal / 100;
if (slideVal == 0) {
/* erase('myCanvas2');
erase('myCanvas3');
erase('myCanvas4');*/
//newSprite('myCanvas1b', 18.8, 45);
newSprite('myCanvas3', 16, 170);
} else if (slideVal > 0 && slideVal <= 34) {
/*erase('myCanvas1');
//erase('myCanvas1b');
erase('myCanvas2');
erase('myCanvas3');
erase('myCanvas4');*/
} else if (slideVal > 34 && slideVal <= 67) {
/*erase('myCanvas1');
erase('myCanvas2');
erase('myCanvas3');
erase('myCanvas4');*/
} else if (slideVal > 67 && slideVal <= 100) {
/*erase('myCanvas1');
erase('myCanvas2');
erase('myCanvas3');
erase('myCanvas4');*/
}
}
function erase(canvasId) {
var canvas = document.getElementById(canvasId);
var context = canvas.getContext("2d");
context.beginPath();
context.clearRect(0, 0, canvas.width, canvas.height);
canvas.width = canvas.width;
}
/**********for backgroundImage********************/
function quadraticCurve(canId, spx, spy, cpx, cpy, endx, endy) {
var canvas = document.getElementById(canId);
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(spx, spy);
ctx.quadraticCurveTo(cpx, cpy, endx, endy);
ctx.strokeStyle = "#eaca2d";
ctx.stroke();
}
function bezierCurve(canId, spx, spy, cpx1, cpy1, cpx2, cpy2, endx, endy) {
var canvas = document.getElementById(canId);
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(spx, spy);
ctx.quadraticCurveTo(cpx1, cpy1, cpx2, cpy2, endx, endy);
ctx.strokeStyle = "#eaca2d";
ctx.stroke();
}
function newSprite(canId, mvx, mvy) {
var canvas = document.getElementById(canId);
var ctx = canvas.getContext('2d');
ctx.globalCompositeOperation = 'source-over';
//ctx.globalCompositeOperation = "destination-over";
ctx.beginPath();
ctx.fillStyle = "#0077c1";
ctx.arc(mvx, mvy, 6, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
}
function drawSlopeCurve1(sID, maxValue) {
// erase('canvasTwo');
var canId = 'myCanvas4';
var slideVal = parseInt(document.getElementById(sID).value);
var canvas = document.getElementById(canId);
var context = canvas.getContext('2d');
canvas.width = canvas.width;
//line end points
x1 = 16;
y1 = 170;
x2 = 200;
y2 = 80;
//get slope (rise over run)
var m = (y2 - y1) / (x2 - x1);
//get y-intercept
var b = y1 - (m * x1);
//get distance between the two points
var distance = Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
//get new x and y values
var x = x1 + parseInt(distance / maxValue * slideVal);
var y = parseInt(m * x + b);
context.beginPath();
context.moveTo(x1, y1);
context.lineTo(x, y);
context.lineWidth = 0.6;
context.stroke();
newSprite(canId, x, y);
}
function drawSlopeCurve2(sID, maxValue) {
// erase('canvasTwo');
var canId = 'myCanvas3';
var slideVal = parseInt(document.getElementById(sID).value);
var canvas = document.getElementById(canId);
var context = canvas.getContext('2d');
canvas.width = canvas.width;
//line end points
x1 = 16;
y1 = 170;
x2 = 160;
y2 = 72;
//get slope (rise over run)
var m = (y2 - y1) / (x2 - x1);
//get y-intercept
var b = y1 - (m * x1);
//get distance between the two points
var distance = Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
//get new x and y values
var x = x1 + parseInt(distance / maxValue * slideVal);
var y = parseInt(m * x + b);
context.beginPath();
context.moveTo(x1, y1);
context.lineTo(x, y);
context.lineWidth = 0.6;
context.stroke();
newSprite(canId, x, y);
}
</script>
</form>
</body>
</html>
This is link for jsfiddle: http://jsfiddle.net/QRVxH/
You should begin by defining the curve in a function, so you can calculate where the graph should end for each x-position. Then you also know where to draw the end-dot.
My demo function has a function to draw a sine on the canvas:
function calc(x){
var y = 100 + ( 50*Math.sin(x*400));
return y;
}
By drawing a line (not a curve!) between the points you get your graph.
for (var x=0; x<=400 && (x <= slider.value); x+=3){
y= calc(x);
ctx.lineTo(x, y);
}
Working demo: http://jsfiddle.net/w1ll3m/CbjWK/11/
Added html5slider.js to make the slider work in firefox.

Categories

Resources