There's any way to replicate this scale behavior in a div ?
Here's an example of the behavior I wanted to reproduce within the div. I already have the movement part, and I just wanted to know about the resizing.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<style>
body {
margin: 0px;
padding: 0px;
}
#wrapper {
position: relative;
border: 1px solid #9C9898;
width: 578px;
height: 200px;
}
#buttonWrapper {
position: absolute;
width: 30px;
top: 2px;
right: 2px;
}
input[type="button"] {
padding: 5px;
width: 30px;
margin: 0px 0px 2px 0px;
}
</style>
<script>
function draw(scale, translatePos) {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
// clear canvas
context.clearRect(0, 0, canvas.width, canvas.height);
context.save();
context.translate(translatePos.x, translatePos.y);
context.scale(scale, scale);
context.beginPath(); // begin custom shape
context.moveTo(-119, -20);
context.bezierCurveTo(-159, 0, -159, 50, -59, 50);
context.bezierCurveTo(-39, 80, 31, 80, 51, 50);
context.bezierCurveTo(131, 50, 131, 20, 101, 0);
context.bezierCurveTo(141, -60, 81, -70, 51, -50);
context.bezierCurveTo(31, -95, -39, -80, -39, -50);
context.bezierCurveTo(-89, -95, -139, -80, -119, -20);
context.closePath(); // complete custom shape
var grd = context.createLinearGradient(-59, -100, 81, 100);
grd.addColorStop(0, "#8ED6FF"); // light blue
grd.addColorStop(1, "#004CB3"); // dark blue
context.fillStyle = grd;
context.fill();
context.lineWidth = 5;
context.strokeStyle = "#0000ff";
context.stroke();
context.restore();
}
window.onload = function() {
var canvas = document.getElementById("myCanvas");
var translatePos = {
x: canvas.width / 2,
y: canvas.height / 2
};
var scale = 1.0;
var scaleMultiplier = 0.8;
var startDragOffset = {};
var mouseDown = false;
// add button event listeners
document.getElementById("plus").addEventListener("click", function() {
scale /= scaleMultiplier;
draw(scale, translatePos);
}, false);
document.getElementById("minus").addEventListener("click", function() {
scale *= scaleMultiplier;
draw(scale, translatePos);
}, false);
// add event listeners to handle screen drag
canvas.addEventListener("mousedown", function(evt) {
mouseDown = true;
startDragOffset.x = evt.clientX - translatePos.x;
startDragOffset.y = evt.clientY - translatePos.y;
});
canvas.addEventListener("mouseup", function(evt) {
mouseDown = false;
});
canvas.addEventListener("mouseover", function(evt) {
mouseDown = false;
});
canvas.addEventListener("mouseout", function(evt) {
mouseDown = false;
});
canvas.addEventListener("mousemove", function(evt) {
if (mouseDown) {
translatePos.x = evt.clientX - startDragOffset.x;
translatePos.y = evt.clientY - startDragOffset.y;
draw(scale, translatePos);
}
});
draw(scale, translatePos);
};
jQuery(document).ready(function() {
$("#wrapper").mouseover(function(e) {
$('#status').html(e.pageX + ', ' + e.pageY);
});
})
</script>
</head>
<body onmousedown="return false;">
<div id="wrapper">
<canvas id="myCanvas" width="578" height="200">
</canvas>
<div id="buttonWrapper">
<input type="button" id="plus" value="+"><input type="button" id="minus" value="-">
</div>
</div>
<h2 id="status">
0, 0
</h2>
</body>
</html>
I tried to use css scale, but it resizes the div too, I want to modify only the space and the elements inside it.
Related
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="style.css" />
<title>Paint, Inc.</title>
</head>
<body>
<div id="sideNav">
</div>
<canvas id="canvas"></canvas>
<script src="canvas.js"></script>
<button id="clear" title="Clear">X</button>
<section id="leftBumper"></section>
<section id="colorChoice">
<input id="color" type="color" value="#000000" />
<label id="colorLabel" for="color">Color</label>
</section>
<section id="strokeWeightChoice">
<input id="strokeWeight" type="range" min="1" max="51" step="5" value="1" list="tickmarks">
<label for="strokeWeight">Thickness</label>
<datalist id="tickmarks">
<option value="1"></option>
<option value="6"></option>
<option value="11"></option>
<option value="16"></option>
<option value="21"></option>
<option value="26"></option>
<option value="31"></option>
<option value="36"></option>
<option value="41"></option>
<option value="46"></option>
<option value="51"></option>
</datalist>
</section>
</body>
</html>
```
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
#canvas {
border: 0.0001px solid white;
}
html {
overflow: hidden;
}
#clear {
position: absolute;
top: 0;
left: 0;
bottom: -10px;
width: 30px;
background: rgba(70, 70, 70, 0.32);
border: rgba(70, 70, 70, 0.32);
border-width: 5px;
font-weight: bold;
font-family: Arial, Helvetica, sans-serif;
font-size: 28px;
color: red;
}
#clear:hover {
transition: 0.4s;
background: rgba(20, 20, 20, 0.4);
cursor: pointer;
font-size: 32px;
}
#clear:focus {
outline: 0;
}
#colorChoice {
position: absolute;
bottom: 0.5rem;
right: 50%;
transform: translateX(50%);
font-family: Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif;
font-weight: bold;
}
#colorChoice:hover {
cursor: pointer;
}
#strokeWeightChoice {
position: absolute;
bottom: 3rem;
right: 50%;
transform: translateX(50%);
font-family: Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif;
font-weight: bold;
}
#strokeWeight {
width: 200px;
}
```
window.addEventListener("load", () => {
const canvas = document.querySelector("#canvas");
const ctx = canvas.getContext("2d");
const color = document.querySelector("#color");
const strokeWeight = document.querySelector("#strokeWeight");
//variables
const clearButton = document.querySelector("#clear");
let painting = false;
function startPosition(e) {
painting = true;
draw(e);
}
function finishedPosition() {
painting = false;
ctx.beginPath();
}
function draw(e) {
if (!painting) return;
ctx.lineCap = "round";
ctx.lineTo(e.clientX, e.clientY);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(e.clientX, e.clientY);
}
function changeColor(e) {
const color = e.target.value;
ctx.strokeStyle = color;
}
function changeStrokeWeight(e) {
const strokeWeight = e.target.value;
ctx.lineWidth = strokeWeight;
}
//Event listeners
canvas.addEventListener("mousedown", startPosition);
canvas.addEventListener("mouseup", finishedPosition);
canvas.addEventListener("mousemove", draw);
color.addEventListener("input", changeColor);
strokeWeight.addEventListener("input", changeStrokeWeight);
//Buttons
clearButton.addEventListener("click", clearCanvas);
function clearCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
});
window.addEventListener("resize", resizeCanvas);
function resizeCanvas() {
//Resizing
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
}
resizeCanvas();
On my canvas whenever I draw while hovering over a button then moving my cursor back to the canvas causes me to draw without pressing until I press again. Could someone please tell me how to fix this glitch. This glitch occurs with my clear button, thickness slider, and my color changer. In addition how do I add something to stop drawing on the clear button.
Let me know if the following change to the javascript will work for you -
When draw() is called by a Mouse Move event it won't check if painting is set to true anymore rather it will check the status of the Mouse Event to see if they are holding down the left click that way when you go off the canvas and hover over one of the buttons and come back onto the canvas it will check to see if you have the left click held down and draw if that's true
Fiddle here if it helps
You can see more about those which properties here
window.addEventListener("load", () => {
const canvas = document.querySelector("#canvas");
const ctx = canvas.getContext("2d");
const color = document.querySelector("#color");
const strokeWeight = document.querySelector("#strokeWeight");
//variables
const clearButton = document.querySelector("#clear");
let painting = false;
function startPosition(e) {
painting = true;
draw(e);
}
function finishedPosition() {
painting = false;
ctx.beginPath();
}
function draw(e) {
//if (!painting) return;
if(e.which == 1){
ctx.lineCap = "round";
ctx.lineTo(e.clientX, e.clientY);
ctx.stroke();
ctx.beginPath();
ctx.moveTo(e.clientX, e.clientY);
}else{
finishedPosition();
}
}
function changeColor(e) {
const color = e.target.value;
ctx.strokeStyle = color;
}
function changeStrokeWeight(e) {
const strokeWeight = e.target.value;
ctx.lineWidth = strokeWeight;
}
//Event listeners
canvas.addEventListener("mousedown", startPosition);
canvas.addEventListener("mouseup", finishedPosition);
canvas.addEventListener("mousemove", draw);
color.addEventListener("input", changeColor);
strokeWeight.addEventListener("input", changeStrokeWeight);
//Buttons
clearButton.addEventListener("click", clearCanvas);
function clearCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
});
window.addEventListener("resize", resizeCanvas);
function resizeCanvas() {
//Resizing
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
}
resizeCanvas();
Basically lol cant add videos here but with the default html color picker you can move the color picker dot if mouse is down off the colors box boundries and it moves agains the edge of the boundries but with mine it just stops moving and doesnt do good when i move the mouse fast.
I am trying to create a custom color picker where you have a slider of colors, then you have the box of the color selected and you can change the whiteness and darkness of it like this here (Like adobe xdcc color picker):
Adobe xdcc color picker example
[The code below creates this here][2]
You can drag the little color picker circle and it changes the selected color but when using canvas I can't have to color picker circle moving around the edges when the mouse leaves the canvas which i would like to change.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
<script src="app.js" defer></script>
</head>
<body>
<h2>Let's Create a Color Picker</h2>
<div class="container">
<canvas id="color-picker"></canvas>
<div class="info">
<h3>Selected Color</h3>
<div class="selected"></div>
</div>
</div>
</body>
</html>
CSS:
html, body {
width: 100%;
height: 100%;
font-family: Oxygen, sans-serif;
text-align: center; }
.container {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center; }
#color-picker {
border: .5px solid rgba(15, 15, 15, 0.2); }
.info {
width: 12em;
display: flex;
margin-left: 4em;
flex-direction: row;
justify-content: space-between; }
.selected {
width: 50px;
height: 50px;
border-radius: 100%;
border: 2px solid rgba(15, 15, 15, 0.2); }
JS:
class Picker {
constructor(target, width, height) {
this.target = target;
this.width = width;
this.height = height;
this.target.width = width;
this.target.height = height;
// Get context
this.context = this.target.getContext("2d");
// Circle
this.pickerCircle = { x: 10, y: 10, width: 10, height: 10 };
this.listenForEvents();
}
draw() {
}
build() {
let gradient = this.context.createLinearGradient(0, 0, this.width, 0);
//Color Stops
gradient.addColorStop(0, "rgb(255, 0, 0)");
gradient.addColorStop(0.15, "rgb(255, 0, 255)");
gradient.addColorStop(0.33, "rgb(0, 0, 255)");
gradient.addColorStop(0.49, "rgb(0, 255, 255)");
gradient.addColorStop(0.67, "rgb(0, 255, 0)");
gradient.addColorStop(0.84, "rgb(255, 255, 0)");
gradient.addColorStop(1, "rgb(255, 0, 0)");
//Fill it
this.context.fillStyle = gradient;
this.context.fillRect(0, 0, this.width, this.height);
//Apply black and white
gradient = this.context.createLinearGradient(0, 0, 0, this.height);
gradient.addColorStop(0, "rgba(255, 255, 255, 1)");
gradient.addColorStop(0.5, "rgba(255, 255, 255, 0)");
gradient.addColorStop(0.5, "rgba(0, 0, 0, 0)");
gradient.addColorStop(1, "rgba(0, 0, 0, 1)");
this.context.fillStyle = gradient;
this.context.fillRect(0, 0, this.width, this.height);
//Circle
this.context.beginPath();
this.context.arc(this.pickerCircle.x, this.pickerCircle.y, this.pickerCircle.width, 0, Math.PI * 2);
this.context.strokeStyle = "black";
this.context.stroke();
this.context.closePath();
}
listenForEvents() {
let isMouseDown = false;
const onMouseDown = (e) => {
this.build();
let currentX = e.clientX - this.target.offsetLeft;
let currentY = e.clientY - this.target.offsetTop;
this.pickerCircle.x = currentX;
this.pickerCircle.y = currentY;
isMouseDown = true;
}
const onMouseMove = (e) => {
if(isMouseDown) {
this.build();
let currentX = e.clientX - this.target.offsetLeft;
let currentY = e.clientY - this.target.offsetTop;
this.pickerCircle.x = currentX;
this.pickerCircle.y = currentY;
}
}
const onMouseUp = () => {
isMouseDown = false;
}
//Register
this.target.addEventListener("mousedown", onMouseDown);
this.target.addEventListener("mousemove", onMouseMove);
this.target.addEventListener("mousemove", () => this.onChangeCallback(this.getPickedColor()));
document.addEventListener("mouseup", onMouseUp);
}
getPickedColor() {
let imageData = this.context.getImageData(this.pickerCircle.x, this.pickerCircle.y, 1, 1);
return { r: imageData.data[0], g: imageData.data[1], b: imageData.data[2] };
}
onChange(callback) {
this.onChangeCallback = callback;
}
}
let picker = new Picker(document.getElementById("color-picker"), 250, 220); picker.build();
picker.onChange((color) => {
let selected = document.getElementsByClassName("selected")[0];
selected.style.backgroundColor = `rgb(${color.r}, ${color.g}, ${color.b})`; });
[1]: https://i.stack.imgur.com/MQsjs.png
[2]: https://i.stack.imgur.com/krEYa.png
Thanks in advance!
the solution is simple, dont use the if(isMouseDown){..}, because that will make your code very unresponsive, so what I did is that I declared a varable let i = 0; then on the onMouseDown, whenever that function is called, it will increment the value of i and I changed the onMouseMove from if(isMouseDown){..} to if(i % 2 === 0){..} heres my solution:
class Picker {
constructor(target, width, height) {
this.target = target;
this.width = width;
this.height = height;
this.target.width = width;
this.target.height = height;
//Get context
this.context = this.target.getContext("2d");
//Circle
this.pickerCircle = { x: 10, y: 10, width: 10, height: 10 };
this.listenForEvents();
}
draw() {
}
build() {
let gradient = this.context.createLinearGradient(0, 0, this.width, 0);
//Color Stops
gradient.addColorStop(0, "rgb(255, 0, 0)");
gradient.addColorStop(0.15, "rgb(255, 0, 255)");
gradient.addColorStop(0.33, "rgb(0, 0, 255)");
gradient.addColorStop(0.49, "rgb(0, 255, 255)");
gradient.addColorStop(0.67, "rgb(0, 255, 0)");
gradient.addColorStop(0.84, "rgb(255, 255, 0)");
gradient.addColorStop(1, "rgb(255, 0, 0)");
//Fill it
this.context.fillStyle = gradient;
this.context.fillRect(0, 0, this.width, this.height);
//Apply black and white
gradient = this.context.createLinearGradient(0, 0, 0, this.height);
gradient.addColorStop(0, "rgba(255, 255, 255, 1)");
gradient.addColorStop(0.5, "rgba(255, 255, 255, 0)");
gradient.addColorStop(0.5, "rgba(0, 0, 0, 0)");
gradient.addColorStop(1, "rgba(0, 0, 0, 1)");
this.context.fillStyle = gradient;
this.context.fillRect(0, 0, this.width, this.height);
//Circle
this.context.beginPath();
this.context.arc(this.pickerCircle.x, this.pickerCircle.y, this.pickerCircle.width, 0, Math.PI * 2);
this.context.strokeStyle = "black";
this.context.stroke();
this.context.closePath();
}
listenForEvents() {
let isMouseDown = true;
let i =0;
const onMouseDown = (e) => {
this.build();
isMouseDown = true
i++
let currentX = e.clientX - this.target.offsetLeft;
let currentY = e.clientY - this.target.offsetTop;
this.pickerCircle.x = currentX;
this.pickerCircle.y = currentY;
}
const onMouseMove = (e) => {
if(i%2 == 0) {
this.build();
let currentX = e.clientX - this.target.offsetLeft;
let currentY = e.clientY - this.target.offsetTop;
this.pickerCircle.x = currentX;
this.pickerCircle.y = currentY;
}
}
const onMouseUp = () => {
isMouseDown = false;
}
//Register
this.target.addEventListener("mousedown", onMouseDown);
this.target.addEventListener("mousemove", onMouseMove);
this.target.addEventListener("mousemove", () => this.onChangeCallback(this.getPickedColor()));
document.addEventListener("mouseup", onMouseUp);
}
getPickedColor() {
let imageData = this.context.getImageData(this.pickerCircle.x, this.pickerCircle.y, 1, 1);
return { r: imageData.data[0], g: imageData.data[1], b: imageData.data[2] };
}
onChange(callback) {
this.onChangeCallback = callback;
}
}
let picker = new Picker(document.getElementById("color-picker"), 250, 220); picker.build();
picker.onChange((color) => {
let selected = document.getElementsByClassName("selected")[0];
selected.style.backgroundColor = `rgb(${color.r}, ${color.g}, ${color.b})`; });
html, body {
width: 100%;
height: 100%;
font-family: Oxygen, sans-serif;
text-align: center; }
.container {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center; }
#color-picker {
border: .5px solid rgba(15, 15, 15, 0.2); }
.info {
width: 12em;
display: flex;
margin-left: 4em;
flex-direction: row;
justify-content: space-between; }
.selected {
width: 50px;
height: 50px;
border-radius: 100%;
border: 2px solid rgba(15, 15, 15, 0.2); }
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
<script src="app.js" defer></script>
</head>
<body>
<h2>Let's Create a Color Picker</h2>
<div class="container">
<canvas id="color-picker"></canvas>
<div class="info">
<h3>Selected Color</h3>
<div class="selected"></div>
</div>
</div>
</body>
</html>
I have an image within a canvas, I want to be to click the image and drag the image(without lifting the left mouse button) and the image at the position where the left mouse button was released. For now as soon as the mouse icon hovers over the canvas, the image moves with it, I tried to add an onclick listener event but I am sure my newbie-ness got in the way of my progress.
Here is what I had come up with so far. How can I make this work with my existing code?
var canvas = document.getElementById('customCanvas');
var context = canvas.getContext('2d');
make_base();
function make_base()
{
upload_image = new Image();
upload_image.src = 'https://lh3.googleusercontent.com/-6Zw-hozuEUg/VRF7LlCjcLI/AAAAAAAAAKQ/A61C3bhuGDs/w126-h126-p/eagle.jpg';
upload_image.onload = function(){
context.drawImage(upload_image, 0, 0);
canvas.addEventListener('click', canvas.onmousemove = function(e) {
/// correct mouse position so its relative to canvas
var rect = canvas.getBoundingClientRect(),
constantX = 0, constantY = 0,
x = e.clientX - rect.left,
y = e.clientY - rect.top;
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(upload_image, x, y);
});
}
}
* {
margin: 0;
padding: 0;
}
html, body {
width: 100%;
height: 100%;
}
.sidepane {
height: 100%;
background: #E8E8EA;
}
.sidepane .form {
height: 80px;
margin: 10px 0;
}
.sidepane .assets {
width: 100%;
}
#assetText {
font-size: 24px;
}
.assets .text, .assets .image {
margin: 10px 0;
}
.assets .image ul li {
width: 50px;
height: 50px;
margin-right: 5px;
float: left;
overflow: hidden;
}
.assets .image ul li img {
width: 100%;
height: 100%;
}
.canvas .block {
position: relative;
width: 600px; height: 600px;
margin: 10px;
border: 1px solid;
box-shadow: 0px 0px 5px black;
}
.item {
border: 1px solid transparent;
position: absolute;
}
.item.selected {
border-color: blue;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="sidepane col-sm-2 col-md-2 col-lg-2">
<form method="post" action="/images" enctype="multipart/form-data">
<!--<div class="form">-->
<h3>Form</h3>
<input type="file" class="form-control" placeholder="Upload Your Images" name="filefield">
<button id="submit" class="btn btn-default">upload</button>
<!-- Upload Form here -->
<!--</div>-->
<hr />
<div class="assets">
<h3>Assets</h3>
<div class="text">
<h4>Text</h4>
<input type="text" name="textfield">
<button id="addText" class="btn btn-default">Add Text</button>
</div>
<div class="image">
<h4>Images</h4>
<ul class="list-unstyled">
<!-- List of images here -->
<!-- <li><img src="images/sample.jpeg" class="img-rounded" /></li> -->
</ul>
</div>
</div>
<input type="submit" >
</form>
</div>
<!-- canvas -->
<div class="canvas col-sm-8 col-md-8 col-lg-8">
<div class="block">
<!-- Add images and texts to here -->
<canvas id="customCanvas" width="598" height="598" style="border: 1px solid #000000">
</canvas>
</div>
</div>
First, you have to check if your mouse is on the image, and then check if you are trying to drag the image. To do that, you need some events, mousedown, mouseup and mousemove. To check if your mouse pointer is on the image, you have to get the X, Y, width, height of that image. Final code below.
Edit
Some more changes. Image class has no X and Y properties so I had to define variables that will store that data and make some changes to isInside function.
var canvas = document.createElement('canvas');
document.body.appendChild(canvas);
var context = canvas.getContext('2d');
canvas.width = 300;
canvas.height = 300;
var upload_image;
var imageX, imageY;
var mouseX, mouseY;
var imageDrag = false;
make_base();
canvas.addEventListener("mousemove", function (evt) {
var mousePos = getMousePos(canvas, evt);
mouseX = mousePos.x;
mouseY = mousePos.y;
});
function getMousePos(canvas, event) {
var rect = canvas.getBoundingClientRect();
return {
x: event.clientX - rect.left,
y: event.clientY - rect.top
};
}
function isInsideImage(rect) {
var pos = { x: mouseX, y: mouseY };
return pos.x > imageX && pos.x < imageX + rect.width && pos.y < imageY + rect.height && pos.y > imageY;
}
function make_base()
{
upload_image = new Image();
imageX = 0;
imageY = 0;
upload_image.onload = function(){
context.drawImage(upload_image, 0, 0);
}
upload_image.src = 'https://lh3.googleusercontent.com/-6Zw-hozuEUg/VRF7LlCjcLI/AAAAAAAAAKQ/A61C3bhuGDs/w126-h126-p/eagle.jpg';
}
canvas.addEventListener("mousedown", function (evt) {
if(isInsideImage(upload_image)) {
imageDrag = true;
}
});
canvas.addEventListener("mouseup", function (evt) {
if(imageDrag)
imageDrag = false;
});
setInterval(function() {
if(imageDrag) {
context.clearRect(0, 0, canvas.width, canvas.height);
imageX = mouseX;
imageY = mouseY;
context.drawImage(upload_image, imageX, imageY);
}
}, 1000/30);
The event you're looking for would be https://developer.mozilla.org/en/docs/Web/Events/mousedown - AFAIK (correct me if I'm wrong) but the click event would only fire when a complete click event has completed (both down and up).
Here's some sample code for this;
var mouseX;
var mouseY; // Accessible outside the function. Easier access to canvas drawing.
var canvas = ''; // Complete this to get canvas element
canvas.addEventListener("mousedown", function(mouse){
// Get mouse co-ordinates
})
Inside this event listener, you can check for your current mouse position...
var canvasElement = element.getBoundingClientRect()
mouseX = mouse.pageX - canvasElement.left;
mouseY = mouse.pageY - canvasElement.top;
Use these variables when drawing your image to the canvas to determine the image's x and y position. These should change as your mouse moves around the canvas. I.e, pass them to your make_base() function;
make_base(mouseX, mouseY)
Update your drawing function to account for them;
function make_base(mouseX, mouseY)
{
upload_image = new Image();
upload_image.src = 'https://lh3.googleusercontent.com/-6Zw-hozuEUg/VRF7LlCjcLI/AAAAAAAAAKQ/A61C3bhuGDs/w126-h126-p/eagle.jpg';
upload_image.onload = function(){
context.drawImage(upload_image, 0, 0);
canvas.addEventListener('click', canvas.onmousemove = function(e) {
/// correct mouse position so its relative to canvas
var rect = canvas.getBoundingClientRect(),
constantX = 0, constantY = 0,
x = mouseX,
y = mouseY
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(upload_image, x, y);
});
}
}
PLEASE NOTE that the code above is not complete, for example, the X and Y will be based on where your mouse is on the PAGE, not the CANVAS. there are separate calculations needed to account for this.
Or, you can just embed an external link under the image to take you to wherever you want!
I'm trying to adjust the size to correctly be position more in the middle and a larger div. I would like it to be 500x500. What I'm trying to do is do a classic version of what Windows Paint is.
The issue is adjusting the 'canvas' to the middle stops the paint brush to 'draw'.
Here is the code, I have so far.
<!DOCTYPE HTML>
<html>
<head>
<style>
body {
width: 500px;
height: 500px;
margin: auto;
top: 50%;
left: 50%;
width: 90%;
border: 3px solid #73AD21;
padding: 10px;
}
</style>
</head>
<body>
<div id="paint" >
<canvas id="myCanvas"></canvas>
</div>
<script>
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var painting = document.getElementById('paint');
var paint_style = getComputedStyle(painting);
canvas.width = parseInt(paint_style.getPropertyValue('width'));
canvas.height = parseInt(paint_style.getPropertyValue('height'));
var mouse = {x: 0, y: 0};
canvas.addEventListener('mousemove', function(e) {
mouse.x = e.pageX - this.offsetLeft;
mouse.y = e.pageY - this.offsetTop;
}, false);
ctx.lineWidth = 10;
ctx.lineJoin = 'round';
ctx.lineCap = 'round';
ctx.strokeStyle = '#00CC99';
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);
var onPaint = function() {
ctx.lineTo(mouse.x, mouse.y);
ctx.stroke();
};
</script>
</body>
</html>
Get rid of the styling on body and replace it with this:
#paint {
height: 500px;
margin: auto;
width: 90%; /* you also had width: 500px, which one did you want? */
border: 3px solid #73AD21;
padding: 10px;
}
Fiddle - Looks like it's working okay with that change.
I'm trying to create an interactive app to enable users to select the shape they want by clicking on the different buttons for the shapes and then enable them to draw the shape wherever they will click on the canvas.
This part is okay but when i click on a different button to draw a shape it seems that the previous shape comes along with the new shape and seems to be overlapped.
Here's the pic:
As you see, the rectangle and the round shape becomes overlapped.
I've tried to use layers of canvas to fix it but now the rectangle button is not working and the rounded shape is not appearing where the user clicks, rather like 30px away from it.
Here's the codes:
<!DOCTYPE html>
<html>
<head>
<script>
function initiateCanvasRectangle()
{
var ctx = document.getElementById('myCanvas1').getContext('2d');
ctx.canvas.addEventListener('mousemove', function(event) {
var mouseX = event.clientX - ctx.canvas.offsetLeft;
var mouseY = event.clientY - ctx.canvas.offsetTop;
});
ctx.canvas.addEventListener('click', function(event) {
var mouseX = event.clientX - ctx.canvas.offsetLeft;
var mouseY = event.clientY - ctx.canvas.offsetTop;
ctx.fillRect(mouseX,mouseY,100,50);
ctx.fillStyle = "purple";
});
}
function initiateCanvasCircle()
{
var ctx = document.getElementById('myCanvas2').getContext('2d');
ctx.canvas.addEventListener('mousemove', function(event) {
var mouseX = event.clientX - ctx.canvas.offsetLeft;
var mouseY = event.clientY - ctx.canvas.offsetTop;
});
ctx.canvas.addEventListener('click', function(event) {
var mouseX = event.clientX - ctx.canvas.offsetLeft;
var mouseY = event.clientY - ctx.canvas.offsetTop;
ctx.beginPath();
ctx.arc(mouseX, mouseY, 30, 0, 2 * Math.PI, false);
ctx.fillStyle = 'pink';
ctx.fill();
});
}
function rect(){
window.addEventListener('click', function(event) {
initiateCanvasRectangle();
});
}
function drawRect()
{
rect();
}
function circle(){
window.addEventListener('click', function(event) {
initiateCanvasCircle();
});
}
function drawCircle()
{
circle();
}
</script>
<style>
BUTTON.rect {
padding: 8px 8px 8px 32px;
font-family: Arial, Verdana;
background-color: white;
border:2px solid black;
}
#tbl {
border-collapse:collapse;
}
</style>
</head>
<body>
<table border="1" id="tbl">
<tr><td><button class="circle" onclick="drawCircle(); return true;" style="padding:20px 40px 20px 40px;">Circle</button>
</td>
<td>
<button class="rect" onclick="drawRect(); return true;" style="padding:20px 40px 20px 40px;"></button>
</td></tr>
</table>
<p>
<div style="position: relative;">
<canvas id="myCanvas1" width="1100" height="400" style="position: absolute; left: 0; top: 0; z-index: 0; border:1px solid black"></canvas>
<canvas id="myCanvas2" width="1100" height="400" style="position: absolute; left: 0; top: 0; z-index: 1;"></canvas>
</div>
</body>
</html>
Can you tell me how to fix it? Any help will be much appreciated. Thanks.